Going on a date with javascript

First things first, the Date object in javascript is misnamed, it represents a date and a time. It should be DateTime instead but that's nowhere near the biggest issue.
</pedantry>

When dealing with dates there are a number of things to remember.
Months are zero indexed, so January in month 0, not month 1. Similarly, month 11 is December, not November.

var date = new Date(2015, 1, 1); // Sun Feb 01 2015 00:00:00 GMT+0000 (GMT Standard Time)

When trying to create a date by passing a string intothe Date contructor, javascript will assume you are using the American format of mm/dd/yy

new Date("02/03/2015") // Tue Feb 03 2015 00:00:00 GMT+0000 (GMT Standard Time)

This means that a European format of dd/mm/yy will result in either an unexpected or invalid date

new Date("12/08/2015") // Tue Dec 08 2015 00:00:00 GMT+0000 (GMT Standard Time) - not the expected 12th of August

new Date("13/08/2015") // Invalid Date

One of the more unusual features of the javascript Date object is that the new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]) constructor will overflow any entires that is outside of it's logical range. This can make date validation unusual, for instance if a user enters a date of 31st February, on a non-leap year it will return the 3rd of March (2nd of March on a leap year)

new Date(2015, 02, 31) // Tue Mar 31 2015 00:00:00 GMT+0100 (GMT Daylight Time)

Strangely, this is actually by design, as mentioned here

Taken to an extreme, this means that you can create a date object representing the 1st of Januray 2016 as the following

new Date(2015, 0, 366) // Fri Jan 01 2016 00:00:00 GMT+0000 (GMT Standard Time)
// Note the zero indexed month to represent January

Dates in javascript are tricky and if you are used to a more structured object like C#'s DateTime you may run into surprises.


Share Tweet Send
0 Comments
Loading...
You've successfully subscribed to SimonReynolds.ie
Great! Next, complete checkout for full access to SimonReynolds.ie
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.