Does a new day in Javascript have a different date style?

I checked the following code in firefox notepad and got an interesting result?

var date=new Date("2012-05-12"); var date2 = new Date("05/12/2012"); date; /* Fri May 11 2012 17:00:00 GMT-0700 (Pacific Daylight Time) */ date2; /* Sat May 12 2012 00:00:00 GMT-0700 (Pacific Daylight Time) */ 

Two dates are different. Apparently, this is due to the time zone problem. I want to get the result of date2. How can I get the js engine to relate properly to the ISO date style?

+6
source share
2 answers

I think the problem is that the string “2012-05-12” is considered the date of ISO 8601, and “05/12/2012” is the date of RFC 2822. In ISO format, the absence of a time zone implies UTC. At midnight on the morning of May 12, in California (or wherever you are), it is 7 pm the night before.

An RFC without a time zone, however, is analyzed on the assumption that you want to use the timestamp at midnight in your local time zone. (Well, not necessarily your time zone, the time zone of the computer your JavaScript is running on :-)

You can see the difference if you pass these lines to Date.parse() .

The RFC date format may include an explicit time zone, but the ISO format cannot. (Well, maybe, but browsers do not pay attention, and, apparently, IE does not cope with them at all.)

edit is a simple (dumb error checking function) here that will give you a date from this ISO three-format form:

 function isoDate( str ) { var rv = null; str.replace(/^(\d\d\d\d)-(\d\d)-(\d\d)$/, function(_, yr, mn, dy) { rv = new Date(parseInt(yr, 10), parseInt(mn, 10) - 1, parseInt(dy, 10)); }); return rv; } 
+2
source

By standard, with Date() , you can parse ISO dates or dates in an implementation-specific format depending on the implementation. To get something more reliable, use a suitable library that can parse dates in some well-known formats.

0
source

Source: https://habr.com/ru/post/918979/


All Articles