Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JavaScript getDate() sometimes return the previous date?

Here are five cases. The results of the last three cases are surprising to me.

// Firefox 40.0.3
// Eastern time zone (ET)

var d;
d = new Date("January 1, 2015");
alert('Month: ' + d.getMonth() + ' Date: ' + d.getDate() + ' UTC: ' + d.toUTCString());
// Month: 0 Date: 1 UTC: Thu, 01 Jan 2015 05:00:00 GMT

d = new Date("January 2, 2015");
alert('Month: ' + d.getMonth() + ' Date: ' + d.getDate() + ' UTC: ' + d.toUTCString());
// Month: 0 Date: 2 UTC: Fri, 02 Jan 2015 05:00:00 GMT

d = new Date("January 1, 2015 00:00:00 GMT");
alert('Month: ' + d.getMonth() + ' Date: ' + d.getDate() + ' UTC: ' + d.toUTCString());
// Month: 11 Date: 31 UTC: Thu, 01 Jan 2015 00:00:00 GMT

d = new Date("2015-01-01");
alert('Month: ' + d.getMonth() + ' Date: ' + d.getDate() + ' UTC: ' + d.toUTCString());
// Month: 11 Date: 31 UTC: Thu, 01 Jan 2015 00:00:00 GMT

d = new Date("2015-01-02");
alert('Month: ' + d.getMonth() + ' Date: ' + d.getDate() + ' UTC: ' + d.toUTCString());
// Month: 0 Date: 1 UTC: Fri, 02 Jan 2015 00:00:00 GMT

It must be some discrepancy between UTC and local time. I see part of the answer. The function getDate() returns the specified date according to local time.

It seems that for getDate(), 00:00:00 GMT is the previous day in local time, so I'm getting the previous date instead of what I expected.

Maybe what I should really be asking is why does the Date constructor sometimes interpret the argument as local time, and sometimes as UTC time? What are rules on that?

jsfiddle

like image 929
Dan Cron Avatar asked Sep 24 '15 19:09

Dan Cron


1 Answers

See the documentation

Specifically - "If a time zone is not specified and the string is in an ISO format recognized by ES5, UTC is assumed. GMT and UTC are considered equivalent. The local time zone is used to interpret arguments in RFC2822 Section 3.3 format (or any format not recognized as ISO 8601 in ES5) that do not contain time zone information"

and

"Given a date string of "March 7, 2014", parse() assumes a local time zone, but given an ISO format such as "2014-03-07" it will assume a time zone of UTC. Therefore Date objects produced using those strings will represent different moments in time unless the system is set with a local time zone of UTC"

The last 2 of your examples are "ISO format recognized by ES5"

like image 192
Preston S Avatar answered Oct 10 '22 19:10

Preston S