· javascript dates

Javascript Dates - Be aware of mutability

It seems that much like in Java, dates in Javascript are mutable, meaning that it is possible to change a date after it has been created.

We had this painfully shown to us when using the datejs library to manipulate some dates.

The erroneous code was similar to this:


var jan312009 = new Date(2008, 1-1, 31);
var oneMonthFromJan312009 = new Date(jan312009.add(1).month());

See the subtle error? Outputting these two values gives the following:


Fri Feb 29 2008 00:00:00 GMT+1100 (EST)
Fri Feb 29 2008 00:00:00 GMT+1100 (EST)

The error is around how we have created the ‘oneMonthFromJan312009’:

var oneMonthFromJan312009 = new Date(jan312009.add(1).month());

We created a new Date but we are also changing the value in ‘jan312009’ as well.

It was the case of having the bracket in the wrong place. It should actually be after the ‘jan312009’ rather than at the end of the statement.

This is the code we wanted:


var jan312009 = new Date(2008, 1-1, 31);
var oneMonthFromJan312009 = new Date(jan312009).add(1).month());

Which leads to more expected results:


Sat Jan 31 2009 00:00:00 GMT+1100 (EST)
Sat Feb 28 2009 00:00:00 GMT+1100 (EST)
  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket