Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript new date treats differently towards different date style?

I tested the following code in firefox scratchpad and got 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 timezone issue. What I want is date2 result. How can I make js engine correctly treats the ISO date style?

like image 896
NSF Avatar asked Jun 25 '12 19:06

NSF


People also ask

How does new Date work JavaScript?

The Date object is an inbuilt datatype of JavaScript language. It is used to work with dates and times. The Date object is created by using new keyword, i.e. new Date(). The Date object can be used date and time in terms of millisecond precision within 100 million days before or after 1/1/1970.

Is new Date () UTC or local?

getTime() returns the number of milliseconds since 1970-01-01. If you create a new Date using this number, ex: new Date(Date. getTime()); it will be UTC, however when you display it (ex: through the chrome dev tools console) it will appear to be your local timezone.

Does new Date () return local time?

"The expression new Date() returns the current time in internal format, as an object containing the number of milliseconds elapsed since the start of 1970 in UTC.

Does new Date return UTC?

The Date object internally stores only a number of milliseconds since 1970-01-01T00:00:00Z (without consideration of leap seconds). In other words, Date objects are always representing the UTC time.


1 Answers

I think the issue is that the string "2012-05-12" is taken to be an ISO 8601 date, while "05/12/2012" is an RFC 2822 date. In the ISO format, the lack of a timezone implies UTC. At midnight on the morning off May 12, in California (or wherever you are) it's 7 PM the previous evening.

The RFC date without a time zone, however, is parsed under the assumption that you want the timestamp for midnight in your local timezone. (Well, not necessarily your timezone; the timezone of the computer where your JavaScript runs :-)

You can see the difference if you pass those strings to Date.parse().

The RFC date format can include an explicit time zone, but the ISO format cannot. (Well, it can, but browsers don't pay attention, and apparently IE doesn't handle those at all.)

edit — here's a simple (dumb; no error checking) function that'll give you a date from that 3-part ISO 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;
}
like image 137
Pointy Avatar answered Nov 15 '22 01:11

Pointy