The JavaScript Date Constructor

Repeat after me: I will not use the Date constructor to parse date strings. By Yihang Ho
Murray Campbell

The JavaScript Date constructor is an overloaded constructor for the Date objects. One of the variants accepts a string as input. This obviously bags the question -- but in what format? If you have worked with date and/or time in the programming context, you might know that representing date and time is a tricky business.

I knew that it is generally not a good idea to ask the Date constructor to parse a date string, since it might not know precisely the format of the string. For example, is 5/9/2018 the 9th of May or the 5th of September? Furthermore, there are timezone variations -- should the string be parsed as local timezone or UTC?

However, I also knew that the Date constructor accepts strings in the ISO 8601 format as well. They look like 2018-11-14T22:44:40. I thought that since the ISO 8601 format is unambiguously defined (including timezone, which is local unless specified) it should be safe to use the Date constructor to parse ISO 8601 date strings. Turns out I am wrong. Safari 12 (Mac & iOS) parses the string as UTC while Chrome 70 and Firefox 63 correctly treats the timezone as local.

The TL;DR:

  1. Don't use the Date constructor to parse human-friendly date strings -- they are ambiguous and the timezone behavior is at best inconsistent.
  2. Don't use the Date constructor to parse the machine-friendly ISO 8601 date strings as well. There are inconsistencies between browsers and will give you the wrong thing.

So what can we do? I guess the best way out is to use a library. I tested date-fns on Safari, Chrome, and Firefox and it works correctly on all of them. For my project, I am fairly certain that the date string I have to parse is well-behaved, so I wrote a regex-based parser instead.