TIL

Today I learned that Javascript dates are all kinds of wonky.

1
2
3
4
» new Date('10/25/2015')
« Sun Oct 25 2015 00:00:00 GMT-0400 (EDT)
» new Date('2015-10-25')
« Sat Oct 24 2015 20:00:00 GMT-0400 (EDT)

The Date constructor interprets a MM-DD-YYYY string as local time, but a YYYY-MM-DD string as UTC time. What a pain. Imagine that you’re working with text-based dates from a database (or worse, from user input) and trying to do some date calculations. Oh, the horror!

Ok, fine, it’s not that bad.

There are problems with two-year dates as well, which aren’t even consistent among themselves:

1
2
3
4
5
6
7
8
9
» new Date(15, 0)
« Fri Jan 01 1915 00:00:00 GMT-0500 (EST)
» new Date('1/1/15')
« Thu Jan 01 2015 00:00:00 GMT-0500 (EST)

» new Date(100, 0)
« Fri Jan 01 100 00:00:00 GMT-0500 (EST)
» new Date('1/1/100')
« Fri Jan 01 100 00:00:00 GMT-0500 (EST)

The solution to these woes, and probably many more like them, are to use a standardizing library like moment.js. Like jQuery, a library is often the best way to write quirk-free, portable code in an environment fractured by varying and unequal implementations of ambiguous specifications.

Code samples were taken straight out of the article from which I learned these things.