Is the output of Date.toString () always in the same format?

As the title says, is the output of Date.toString() (more precisely, Date.toTimeString() ) always in the same format in all browsers?

I ask about this since the EMCAScript specification says that "the contents of the string are implementation dependent."


I need to verify this, because I need to format the string by inserting HTML span elements as follows:

(new Date()).toTimeString().replace(" GMT", "<span id='offset'> GMT") + '</span>' );

This will create (in Google Chrome v28.0.1500.95) something like

18:19:26<span id="offset"> GMT-0700 (Pacific Daylight Time)</span>

which I can then using CSS.


Suggestions on the best ways to create output will also be great!

+7
javascript date datetime
source share
2 answers

In short, no, toString does not always output the same format.

 new Date().toString() 

prints

  • "Sat 02/11/2012 02:15:10 GMT + 0100" in Firefox 10
  • "Sat 11/02/2012 02:18:29 GMT + 0100 (standard time W. Europe)" in Chrome 16
  • "Sat Feb 11 02:18:59 UTC + 0100 2012" in Internet Explorer 9

I know this is an earlier version of the browser, but it shows that it is browser dependent.

However, when using toTimeString() it always starts with hours: minutes: seconds [space] ...

Therefore, you could split the line into 2 parts based on the first [space] with:

indexOf(" ")

Then wrap the second part with your range

Moment does some string formatting of dates, but also does not handle your requested offset string very well, since it depends on toString ().

I hope this helps

+3
source share

Moment.js is a good date formatting library in JS. https://github.com/moment/moment

Otherwise, yes, you ended up disassembling it yourself, as browsers render it differently.

-one
source share

All Articles