addDays() in Javascript

Posted by Jarren Long at 2015-01-23 15:05:17

So I was working on some more fancy pants graphing stuff for my Electric Vehicle Charger project, when I came across the need to add and subtract days from a Javascript Date() object. Being crappy at Javascript...Stack Overflow to the rescue! (http://stackoverflow.com/questions/563406/add-days-to-datetime). Sadly, this solution IS INCORRECT!!! As noted in the comments, this does not work for situations where the Month and Year are different (example: adding 1 day to 12/31/2014 would give you 1/1/2014, not 2015...). So, here's the CORRECT way to do it:

// Incorrect
Date.prototype.addDays = function(days) {

    var dat = new Date(this.valueOf()); // Get a copy of the Date being modified
    dat.setDate(dat.getDate() + days); // Add days to the day of the month
    return dat; // Return the new Date
}
var date = new Date(0).addDays(1);
// date = 1/2/1970

// Correct
Date.prototype.addDays = function(days) {
    var dat = new Date(this.valueOf()); // Get a copy of the Date being modified
    // Convert the date to Milliseconds since 1970 (epoch time * 1000)
    dat.setTime(dat.getTime() + (days * 60 * 60 * 1000)); // Add days (convert to milliseconds) to the entire Date
    return dat; // Return the new Date
}
var date = new Date(0).addDays(1); // date = 1/2/1970