TinyTimZamboni
TinyTimZamboni

Reputation: 5345

Date(dateString) constructor inconsistent?

a = new Date('09-01-2013')
//Sun Sep 01 2013 00:00:00 GMT-0400 (EDT)

b = new Date('2013-09-01')
//Sat Aug 31 2013 20:00:00 GMT-0400 (EDT)

b < a
//true

I did this in the Node.js repl, v0.10.12

Why are the dates different based on the form of the dateString?

I can't see how this is timezone related, since both dates are displayed in local timezone and their values are clearly not equivalent.

Upvotes: 0

Views: 113

Answers (1)

sushain97
sushain97

Reputation: 2802

The problem is that new Date('09-01-2013') and new Date('2013-09-01') use different formats/standards and as such are parsed differently.

new Date('09-01-2013') is parsed as you would expect and results in a midnight time (in your local time zone). However, new Date('2013-09-01') is parsed as an ISO-8601 date at UTC midnight, UTC midnight is then converted to your local timezone when displayed (in this case EDT which is reflected in the 20:00:00, a 4 hour difference).

Conclusion: use YYYY/MM/DD to avoid headaches.

Upvotes: 1

Related Questions