1

I was surprised to realize that

new Date('2015-02-15') and new Date('02-15-2015') return different results. One parses the date as midnight UTC time, the other is parsed as midnight local time. This is also true of the moment-timezone package.

Is there a way to parse these dates in a standard way, either using moment or the builtin Date?

Colin McDonnell
  • 897
  • 1
  • 11
  • 17
  • 2
    1) `new Date(string)` is very unreliable anf has a lot of "legacy features". 2) There are a few ISO specifications for dates, `new Date().toString()` shows one of them (that is reliably parsed) – Jonas Wilms May 17 '19 at 22:39
  • In the case of YYYY-MM-DD, the [*TC39*](https://github.com/tc39/ecma262/issues/87) decided to break with ISO 8601 and parse it as UTC rather than local. As for DD-MM-YYYY, parsing is implementation dependent. You can parse them with any library by providing the format of the string to parse, or write a simple parse function (2 or 3 lines of code). – RobG May 18 '19 at 21:40

1 Answers1

2

Passing expected date string format to moment.js seem to return the same local timezone

// Sun Feb 15 2015 00:00:00 GMT-0800
moment('2015-02-15', 'YYYY-MM-DD').toString()
// Sun Feb 15 2015 00:00:00 GMT-0800
moment('02-15-2015', 'MM-DD-YYYY').toString()

You can use moment-timezone package for standardizing the time into UTC for example

// Sun Feb 15 2015 08:00:00 GMT+0000
moment('2015-02-15', 'YYYY-MM-DD').utc().toString()
// Sun Feb 15 2015 08:00:00 GMT+0000
moment('02-15-2015', 'MM-DD-YYYY').utc()toString()

Try it out: https://jsfiddle.net/wyopm3xu/

Atsushi
  • 341
  • 3
  • 11