Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

javascript - Inconsistent behavior of toLocaleString() in different browser

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 GMTO (e)"

The syntax for DateJS is:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...