Javascript date gotcha

When you instantiate dates in javascript, if you do it using the string constructor (e.g. new Date('2013-06-01')), you’re effectively calling the Date.parse function.
Date.parse is implementation dependent, which means you’ll end up with a different date value depending on what is executing your javascript (for instance Firefox or Chrome).

The results can be catastrophic when you’re grouping stuff by day and you’re instancing date with just the day component coming as a JSON serialised value like '2013-06-01T00:00'.

If you want your dates to behave, always use the constructor that creates dates from int values (e.g. new Date(2013, 5, 1)). And remember: the month parameter is zero based (0 represents January)!

I discovered this gotcha whilst developing a calendar visualisation for watchdogapp.com (using D3.js).

Visualisation parsing the date with the string constructor (Chrome):

chrome-date-using-string-constructor

Visualisation parsing the date with the ‘int’ constructor (Chrome):

chrome-date-using-int-constructor

You can see on the two visualisations above that in Chrome, parsing a date from a string does something extra (probably to do with summer time offset)!