Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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


I need to make sure of 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 would produce (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 style with CSS.


Suggestions for better ways to style the output would also be great!

like image 907
Alfred Xing Avatar asked Aug 02 '13 01:08

Alfred Xing


People also ask

How do I format a date string?

The string format should be: YYYY-MM-DDTHH:mm:ss. sssZ , where: YYYY-MM-DD – is the date: year-month-day. The character "T" is used as the delimiter.

How many formats are there for displaying date and time?

Dear Mate ! The dates appear as, mm/dd/yyyy in the U.S. and as, dd/mm/yyyy outside the U.S. where mm is the month, dd is the day, and yyyy is the year. The time is displayed as, hh:mm:ss AM/PM, where hh is the hour, mm is minutes, and ss is seconds. Hope this answer helps you.

What is the universal date format?

The ISO standard takes a general-to-specific approach for its date formats: The year comes first, followed by the month and then by the day of the month, with most elements represented as numerical values. For example, the ISO representation for July 15, 2022 is either 20220715 or 2022-07-15.


1 Answers

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

new Date().toString() 

prints

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

I know these are older browser version, but it shows that it is browser dependent.

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

Therefore, you could instead split the string into 2 portions based on the first [space] with:

indexOf(" ")

Then wrap the second portion with your span

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

I hope that helps

like image 165
PostureOfLearning Avatar answered Sep 17 '22 18:09

PostureOfLearning