What is the best way to display date values formatted with users locale with JavaScript Remoting?

If you query a Date or a DateTime field with JavaScript Remoting the value returned will be the number of milliseconds since 1970 such as, 1359147598000. Good for data consistency…bad for user experience.

var date = new Date(1359147598000);
console.log(date);
console.log(date.toDateString());
console.log(date.toLocaleDateString());

Will result the following output:

Fri Jan 25 2013 12:59:58 GMT-0800 (PST)
Fri Jan 25 2013
1/25/2013

For United States users the date should format as 1/25/2013. For the mates in UK it should format as 25/01/2013.

You would think toLocaleDateString() would be the solution but it appears very brittle and it doesn’t even seem to work for when I change my computers locale.

So what is the best way to format and display Date/DateTime values in the users local format when using JavaScript Remoting?

Thanks.

Answer

I’d recommend any JavaScript date library in conjunction with UserContext.dateFormat. As you say, browser locale implementations are pretty brittle. The display on the client should be completely independent of the underlying value and whether or not it was remoted 🙂

Edit: or carefully take advantage of the DateUtil object already present (courtesy @TehNrd)

From the comments:
DateUtil.getDateTimeStringFromUserLocale(d); and DateUtil.getDateStringFromUserLocale(d); I’d recommend wrapping them in a try catch as they could change at anytime.

Attribution
Source : Link , Question Author : TehNrd , Answer Author : Daniel Hoechst

Leave a Comment