Traps With Javascript Date Objects

2016-03-28 | #helper, #javascript, #webdev

There are several nasty specialties of Javascript date objects you should keep in mind when dealing with them.

The first and most common trap is the fact that Javascript counts months zero based (in contrast to other date parts).

var d = new Date();

d.getMonth();

=> 0-11

Additionally "d.getYear()" isn't what you'd expect, unless you expect to get 116 instead of 2016. What you are searching for is called "d.getFullYear()".

Another problem you'll discover when you try to parse a string into a date is that although the possibilities and formats are plentysome you'll have real problems with finding a date representation that all browsers accept and that is not at least partly unclear such as "8/6/2001". After some fiddling around you'll get to the point where you'll accept that the securest way to get to a date object from a string is to use iso-dates and only iso-dates.

But even with those you'll have to keep some things in mind. You can not leave out leading zeroes, since firefox will produce an invalid date without them. You can not use timezone notation, since IE9 doesn't know what to do with them. And you cannot leave out the "T" between the date and time part, since Firefox needs it.

// don't do this

new Date('2001-1-31');

new Date('2001-01-31 12:00:00');

new Date('2001-01-31T12:00:00Z');

new Date('2001-01-31T12:00:00+01);

// do this

new Date('2001-01-31T12:00:00');

Handling timezones may require some fiddling with the base string as well as setting it after parsing on the date object.

The only helpful thing you can memorize about Javascript date objects is the fact that all central methods have a UTC-counterpart. So there is also getUTCDate, getUTCFullYear, and so on. That makes it relatively easy to retrieve neutral date representations from client date objects. Just bear in mind that locally created date objects are always automatically local, so only use those functions exclusively when dealing with provided UTC-dates.