[javascript] How to subtract days from a plain Date?

Is there an easy way of taking a olain JavaScript Date (e.g. today) and going back X days?

So, for example, if I want to calculate the date 5 days before today.

This question is related to javascript date

The answer is


I like doing the maths in milliseconds. So use Date.now()

var newDate = Date.now() + -5*24*3600*1000; // date 5 days ago in milliseconds

and if you like it formatted

new Date(newDate).toString(); // or .toUTCString or .toISOString ...

NOTE: Date.now() doesn't work in older browsers (eg IE8 I think). Polyfill here.

UPDATE June 2015

@socketpair pointed out my sloppiness. As s/he says "Some day in year have 23 hours, and some 25 due to timezone rules".

To expand on that, the answer above will have daylightsaving inaccuracies in the case where you want to calculate the LOCAL day 5 days ago in a timezone with daylightsaving changes and you

  • assume (wrongly) that Date.now() gives you the current LOCAL now time, or
  • use .toString() which returns the local date and therefore is incompatible with the Date.now() base date in UTC.

However, it works if you're doing your math all in UTC, eg

A. You want the UTC date 5 days ago from NOW (UTC)

var newDate = Date.now() + -5*24*3600*1000; // date 5 days ago in milliseconds UTC
new Date(newDate).toUTCString(); // or .toISOString(), BUT NOT toString

B. You start with a UTC base date other than "now", using Date.UTC()

newDate = new Date(Date.UTC(2015, 3, 1)).getTime() + -5*24*3600000;
new Date(newDate).toUTCString(); // or .toISOString BUT NOT toString

var my date = new Date().toISOString().substring(0, 10);

it can give you only date like 2014-06-20. hope will help


If you want to both subtract a number of days and format your date in a human readable format, you should consider creating a custom DateHelper object that looks something like this :

_x000D_
_x000D_
var DateHelper = {_x000D_
    addDays : function(aDate, numberOfDays) {_x000D_
        aDate.setDate(aDate.getDate() + numberOfDays); // Add numberOfDays_x000D_
        return aDate;                                  // Return the date_x000D_
    },_x000D_
    format : function format(date) {_x000D_
        return [_x000D_
           ("0" + date.getDate()).slice(-2),           // Get day and pad it with zeroes_x000D_
           ("0" + (date.getMonth()+1)).slice(-2),      // Get month and pad it with zeroes_x000D_
           date.getFullYear()                          // Get full year_x000D_
        ].join('/');                                   // Glue the pieces together_x000D_
    }_x000D_
}_x000D_
_x000D_
// With this helper, you can now just use one line of readable code to :_x000D_
// ---------------------------------------------------------------------_x000D_
// 1. Get the current date_x000D_
// 2. Subtract 5 days_x000D_
// 3. Format it_x000D_
// 4. Output it_x000D_
// ---------------------------------------------------------------------_x000D_
document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), -5));
_x000D_
_x000D_
_x000D_

(see also this Fiddle)


Using Modern JavaScript function syntax

_x000D_
_x000D_
const getDaysPastDate = (daysBefore, date = new Date) => new Date(date - (1000 * 60 * 60 * 24 * daysBefore));_x000D_
_x000D_
console.log(getDaysPastDate(1)); // yesterday
_x000D_
_x000D_
_x000D_


The top answers led to a bug in my code where on the first of the month it would set a future date in the current month. Here is what I did,

curDate = new Date(); // Took current date as an example
prvDate = new Date(0); // Date set to epoch 0
prvDate.setUTCMilliseconds((curDate - (5 * 24 * 60 * 60 * 1000))); //Set epoch time

A easy way to manage dates is use Moment.js

You can use add. Example

var startdate = "20.03.2014";
var new_date = moment(startdate, "DD.MM.YYYY");
new_date.add(5, 'days'); //Add 5 days to start date
alert(new_date);

Docs http://momentjs.com/docs/#/manipulating/add/


_x000D_
_x000D_
function addDays (date, daysToAdd) {_x000D_
  var _24HoursInMilliseconds = 86400000;_x000D_
  return new Date(date.getTime() + daysToAdd * _24HoursInMilliseconds);_x000D_
};_x000D_
_x000D_
var now = new Date();_x000D_
_x000D_
var yesterday = addDays(now, - 1);_x000D_
_x000D_
var tomorrow = addDays(now, 1);
_x000D_
_x000D_
_x000D_


It goes something like this:

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

I find a problem with the getDate()/setDate() method is that it too easily turns everything into milliseconds, and the syntax is sometimes hard for me to follow.

Instead I like to work off the fact that 1 day = 86,400,000 milliseconds.

So, for your particular question:

today = new Date()
days = 86400000 //number of milliseconds in a day
fiveDaysAgo = new Date(today - (5*days))

Works like a charm.

I use this method all the time for doing rolling 30/60/365 day calculations.

You can easily extrapolate this to create units of time for months, years, etc.


Without using the second variable, you can replace 7 for with your back x days:

let d=new Date(new Date().getTime() - (7 * 24 * 60 * 60 * 1000))

A few of the existing solutions were close, but not quite exactly what I wanted. This function works with both positive or negative values and handles boundary cases.

function addDays(date, days) {
    return new Date(
        date.getFullYear(),
        date.getMonth(),
        date.getDate() + days,
        date.getHours(),
        date.getMinutes(),
        date.getSeconds(),
        date.getMilliseconds()
    );
}

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");

Use MomentJS.

_x000D_
_x000D_
function getXDaysBeforeDate(referenceDate, x) {_x000D_
  return moment(referenceDate).subtract(x , 'day').format('MMMM Do YYYY, h:mm:ss a');_x000D_
}_x000D_
_x000D_
var yourDate = new Date(); // let's say today_x000D_
var valueOfX = 7; // let's say 7 days before_x000D_
_x000D_
console.log(getXDaysBeforeDate(yourDate, valueOfX));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
_x000D_
_x000D_
_x000D_


You can using Javascript.

var CurrDate = new Date(); // Current Date
var numberOfDays = 5;
var days = CurrDate.setDate(CurrDate.getDate() + numberOfDays);
alert(days); // It will print 5 days before today

For PHP,

$date =  date('Y-m-d', strtotime("-5 days")); // it shows 5 days before today.
echo $date;

Hope it will help you.


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();
weekDate.setTime(todayDate.getTime()-(7*24*3600000));

See the following code, subtract the days from the current date. Also, set the month according to substracted date.

var today = new Date();
var substract_no_of_days = 25;

today.setTime(today.getTime() - substract_no_of_days* 24 * 60 * 60 * 1000);
var substracted_date = (today.getMonth()+1) + "/" +today.getDate() + "/" + today.getFullYear();

alert(substracted_date);

If you want it all on one line instead.

5 days from today

//past
var thirtyDaysAgo = new Date(new Date().setDate(new Date().getDate() - 5));
//future
var thirtyDaysInTheFuture = new Date(new Date().setDate(new Date().getDate() + 5));

5 days from a specific date

 var pastDate = new Date('2019-12-12T00:00:00');

 //past
 var thirtyDaysAgo = new Date(new Date().setDate(pastDate.getDate() - 5));
 //future
 var thirtyDaysInTheFuture = new Date(new Date().setDate(pastDate.getDate() + 5));

I wrote a function you can use.

_x000D_
_x000D_
function AddOrSubractDays(startingDate, number, add) {_x000D_
  if (add) {_x000D_
    return new Date(new Date().setDate(startingDate.getDate() + number));_x000D_
  } else {_x000D_
    return new Date(new Date().setDate(startingDate.getDate() - number));_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log('Today : ' + new Date());_x000D_
console.log('Future : ' + AddOrSubractDays(new Date(), 5, true));_x000D_
console.log('Past : ' + AddOrSubractDays(new Date(), 5, false));
_x000D_
_x000D_
_x000D_


I get good mileage out of date.js:

http://www.datejs.com/

d = new Date();
d.add(-10).days();  // subtract 10 days

Nice!

Website includes this beauty:

Datejs doesn’t just parse strings, it slices them cleanly in two


When setting the date, the date converts to milliseconds, so you need to convert it back to a date:

This method also take into consideration, new year change etc.

function addDays( date, days ) {
    var dateInMs = date.setDate(date.getDate() - days);
    return new Date(dateInMs);
}

var date_from = new Date();
var date_to = addDays( new Date(), parseInt(days) );

I have created a function for date manipulation. you can add or subtract any number of days, hours, minutes.

function dateManipulation(date, days, hrs, mins, operator) {
   date = new Date(date);
   if (operator == "-") {
      var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
      var newDate = new Date(date.getTime() - durationInMs);
   } else {
      var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
      var newDate = new Date(date.getTime() + durationInMs);
   }
   return newDate;
 }

Now, call this function by passing parameters. For example, here is a function call for getting date before 3 days from today.

var today = new Date();
var newDate = dateManipulation(today, 3, 0, 0, "-");

var daysToSubtract = 3;
$.datepicker.formatDate('yy/mm/dd', new Date() - daysToSubtract) ;

To calculate relative time stamps with a more precise difference than whole days, you can use Date.getTime() and Date.setTime() to work with integers representing the number of milliseconds since a certain epoch—namely, January 1, 1970. For example, if you want to know when it’s 17 hours after right now:

_x000D_
_x000D_
const msSinceEpoch = (new Date()).getTime();
const fortyEightHoursLater = new Date(msSinceEpoch + 48 * 60 * 60 * 1000).toLocaleString();
const fortyEightHoursEarlier = new Date(msSinceEpoch - 48 * 60 * 60 * 1000).toLocaleString();
const fiveDaysAgo = new Date(msSinceEpoch - 120 * 60 * 60 * 1000).toLocaleString();

console.log({msSinceEpoch, fortyEightHoursLater, fortyEightHoursEarlier, fiveDaysAgo})
_x000D_
_x000D_
_x000D_

reference


_x000D_
_x000D_
var d = new Date();_x000D_
_x000D_
document.write('Today is: ' + d.toLocaleString());_x000D_
_x000D_
d.setDate(d.getDate() - 31);_x000D_
_x000D_
document.write('<br>5 days ago was: ' + d.toLocaleString());
_x000D_
_x000D_
_x000D_


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:

http://simonwillison.net/2007/Dec/3/datejs/


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

if(!Date.prototype.adjustDate){
    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.getFullYear(),
                this.getMonth(),
                this.getDate() - Math.abs(days),
                this.getHours(),
                this.getMinutes(),
                this.getSeconds(),
                this.getMilliseconds()
            );
        }

        this.setTime(date.getTime());

        return this;
    };
}

So, to use it i can simply write:

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

for me all the combinations worked fine with below code snipplet , the snippet is for Angular-2 implementation , if you need to add days , pass positive numberofDays , if you need to substract pass negative numberofDays

function addSubstractDays(date: Date, numberofDays: number): Date {
let d = new Date(date);
return new Date(
    d.getFullYear(),
    d.getMonth(),
    (d.getDate() + numberofDays)
);
}

This will give you last 10 days result 110% working you will not get any type of issue

var date = new Date();
var day=date.getDate();
var month=date.getMonth() + 1;
var year=date.getFullYear();
var startDate=day+"/"+month+"/"+year;
var dayBeforeNineDays=moment().subtract(10, 'days').format('DD/MM/YYYY');
startDate=dayBeforeNineDays;
var endDate=day+"/"+month+"/"+year;

you can change the subtract days according to your requirements


Try something like this

dateLimit = (curDate, limit) => {
    offset  = curDate.getDate() + limit
    return new Date( curDate.setDate( offset) )
}

currDate could be any date

limit could be the difference in number of day (positive for future and negative for past)


_x000D_
_x000D_
var date = new Date();_x000D_
var day = date.getDate();_x000D_
var mnth = date.getMonth() + 1;_x000D_
_x000D_
var fDate = day + '/' + mnth + '/' + date.getFullYear();_x000D_
document.write('Today is: ' + fDate);_x000D_
var subDate = date.setDate(date.getDate() - 1);_x000D_
var todate = new Date(subDate);_x000D_
var today = todate.getDate();_x000D_
var tomnth = todate.getMonth() + 1;_x000D_
var endDate = today + '/' + tomnth + '/' + todate.getFullYear();_x000D_
document.write('<br>1 days ago was: ' + endDate );
_x000D_
_x000D_
_x000D_


I converted into millisecond and deducted days else month and year won't change and logical

var numberOfDays = 10;//number of days need to deducted or added
var date = "01-01-2018"// date need to change
var dt = new Date(parseInt(date.substring(6), 10),        // Year
              parseInt(date.substring(3,5), 10) - 1, // Month (0-11)
              parseInt(date.substring(0,2), 10));
var new_dt = dt.setMilliseconds(dt.getMilliseconds() - numberOfDays*24*60*60*1000);
new_dt = new Date(new_dt);
var changed_date = new_dt.getDate()+"-"+(new_dt.getMonth()+1)+"-"+new_dt.getFullYear();

Hope helps


split your date into parts, then return a new Date with the adjusted values

function DateAdd(date, type, amount){
    var y = date.getFullYear(),
        m = date.getMonth(),
        d = date.getDate();
    if(type === 'y'){
        y += amount;
    };
    if(type === 'm'){
        m += amount;
    };
    if(type === 'd'){
        d += amount;
    };
    return new Date(y, m, d);
}

Remember that the months are zero based, but the days are not. ie new Date(2009, 1, 1) == 01 February 2009, new Date(2009, 1, 0) == 31 January 2009;


I like the following because it is one line. Not perfect with DST changes but usually good enough for my needs.

var fiveDaysAgo = new Date(new Date() - (1000*60*60*24*5));