Inconsistent behavior of toLocaleString() in different browser

Ishan Dhingra picture Ishan Dhingra · Nov 17, 2012 · Viewed 24.5k times · Source

I am working on a project where I have to deal a lot with Date and Time. Server side technology is ASP.Net and at client side I am using jQuery and jQuery Week Calendar(a jQuery plugin).

So here is the problem described, I am receiving Data Time from server something like this 2012-11-13T04:45:00.00 in GMT format.

Now at client side, I want this Date Time to be converted to Locale Date Time Format, like whatever is could be IST, EST, PKT, etc.

To achieve this, I am using JavaScript method toLocaleString(). This only works fine in Chrome, in other browser it works inconsistently.

Here are its outputs in different browsers:

Google Chrome(Works fine):

Call:

new Date ("2012-11-13T04:45:00.00").toLocaleString();

Output:

Tue Nov 13 2012 10:15:00 GMT+0530 (India Standard Time)

Mozilla Firefox:

Call:

new Date ("2012-11-13T04:45:00.00").toLocaleString();

Output:

Tuesday, November 13, 2012 4:45:00 AM

Safari:

Call:

new Date ("2012-11-13T04:45:00.00").toLocaleString();

Output:

Invalid Date

Internet Explorer:

Call:

new Date ("2012-11-13T04:45:00.00").toLocaleString();

Output:

Tuesday, November 13, 2012 4:45:00 AM

For now these are the browsers where I tested.

Here is the Question:

I need a way to convert Data Time(having format like this 2012-11-13T04:45:00.00) To Locale Date and Time, no matter which browser client is using.

Answer

funwhilelost picture funwhilelost · Nov 21, 2012

The short answer is no. toLocaleString can be implemented however the developers wish. What your question implies is that Chrome outputs the string you want.

If you would like to output that format consistently you'll need to use a separate library - like DateJS.

To do this with DateJS will need some standard format specifiers available in core.js and some that are only available in extras.js. The documentation has a list of all the format specifiers.

The string you want is:

Tue Nov 13 2012 10:15:00 GMT+0530 (India Standard Time)

So to get this from DateJS you'll need:

"D M d Y H:i:s \G\M\TO (e)"

The syntax for DateJS is:

new Date ("2012-11-13T04:45:00.00").format("D M d Y H:i:s \G\M\TO (e)");