Subtract days from a date in JavaScript

Subtract days from a date in JavaScript

Does anybody know of an easy way of taking a date (e.g. Today) and going back X days?
So, for example, if I want to calculate the date 5 days before today.


Solution 1:

Try something like this:

 var d = new Date();

Note that this modifies the date object and returns the time value of the updated date.

var d = new Date();

document.write('Today is: ' + d.toLocaleString());

d.setDate(d.getDate() - 5);

document.write('<br>5 days ago was: ' + d.toLocaleString());

Solution 2:

var dateOffset = (24*60*60*1000) * 5; //5 days
var myDate = new Date();
myDate.setTime(myDate.getTime() - dateOffset);

If you’re performing lots of headachy date manipulation throughout your web application, DateJS will make your life much easier:

Solution 3:

It goes something like this:

var d = new Date(); // today!
var x = 5; // go back 5 days!
d.setDate(d.getDate() - x);

Solution 4:

I noticed that the getDays+ X doesn’t work over day/month boundaries. Using getTime works as long as your date is not before 1970.

var todayDate = new Date(), weekDate = new Date();

Solution 5:

get moment.js. All the cool kids use it. It has more formatting options, etc. Where

var n = 5;
var dateMnsFive = moment(<your date>).subtract(n , 'day');

Optional! Convert to JS Date obj for Angular binding.

var date = new Date(dateMnsFive.toISOString());

Optional! Format

var date = dateMnsFive.format("YYYY-MM-DD");

Solution 6:

I made this prototype for Date so that I could pass negative values to subtract days and positive values to add days.

    Date.prototype.adjustDate = function(days){
        var date;

        days = days || 0;

        if(days === 0){
            date = new Date( this.getTime() );
        } else if(days > 0) {
            date = new Date( this.getTime() );

            date.setDate(date.getDate() + days);
        } else {
            date = new Date(
                this.getDate() - Math.abs(days),


        return this;

So, to use it i can simply write:

var date_subtract = new Date().adjustDate(-4),
    date_add = new Date().adjustDate(4);