0

Can anybody explain the following behaviour with dash-separated dates?

console.log(new Date('2015/03/03'));
Tue Mar 03 2015 00:00:00 GMT+0000 (GMT Standard Time)

console.log(new Date('2015-03-03'));
Tue Mar 03 2015 00:00:00 GMT+0000 (GMT Standard Time)

console.log(new Date('2015/04/03'));
Fri Apr 03 2015 00:00:00 GMT+0100 (GMT Daylight Time)

console.log(new Date('2015-04-03'));
Fri Apr 03 2015 01:00:00 GMT+0100 (GMT Daylight Time) // This is the weird one

Note: I am on UK, so GMT+0 during winter, GMT+1 during "summer".

Note 2: I've read I should use '/' as a separator, specially as IE11 does not do it but I am wondering how that can happen in Chrome?

Note 3: In NodeJS it gets even weirder.

console.log(new Date('2015/03/03'));
2015-03-03T00:00:00.000Z

console.log(new Date('2015-03-03'));
2015-03-03T00:00:00.000Z

console.log(new Date('2015/04/03'));
2015-04-02T23:00:00.000Z //This is the weird one this time

console.log(new Date('2015-04-03'));
2015-04-03T00:00:00.000Z
Chexpir
  • 1,876
  • 18
  • 33

1 Answers1

3

It seems weird and it's because some of the dates are interpreted as partial ISO dates (those with dashes) and they get interpreted as UTC, and other are parsed magically and get interpreted as local time zone.

That's why I always recommend using Moment for date parsing with always providing the format that you're expecting explicitly and always using true as the third argument to moment() for strict validation, to avoid any possible misinterpretations because putting wrong data to your database is worse than crashing, and dates can be critical in many places.

Examples:

console.log( moment('2015/03/03', 'YYYY/MM/DD', true).toISOString() );
2015-03-02T23:00:00.000Z

console.log( moment('2015-03-03', 'YYYY-MM-DD', true).toISOString() );
2015-03-02T23:00:00.000Z

console.log( moment('2015/04/03', 'YYYY/MM/DD', true).toISOString() );
2015-04-02T22:00:00.000Z

console.log( moment('2015-04-03', 'YYYY-MM-DD', true).toISOString() );
2015-04-02T22:00:00.000Z

As you can see, no surprises here.

For more info on how and why to validate dates, see this answer:

Community
  • 1
  • 1
rsp
  • 107,747
  • 29
  • 201
  • 177