Finding date by subtracting X number of days from a particular date in Javascript

Viewed 51399

I want to find date by subtracting X number of days from a particular date in JavaScript. My JavaScript function accepts 2 parameters. One is the date value and the other is the number of days that needs to be subtracted.

For example, I pass my argument date as 27 July 2009 and i pass my other argument as 3. So i want to calculate the date 3 days before 27 July 2009. So the resultant date that we should get is 24 July 2009. How is this possible in JavaScript. Thanks for any help.

9 Answers

Simply:

yourDate.setDate(yourDate.getDate() - daysToSubtract);
function date_by_subtracting_days(date, days) {
    return new Date(
        date.getFullYear(), 
        date.getMonth(), 
        date.getDate() - days,
        date.getHours(),
        date.getMinutes(),
        date.getSeconds(),
        date.getMilliseconds()
    );
}

Here's an example, however this does no kind of checking (for example if you use it on 2009/7/1 it'll use a negative day or throw an error.

function subDate(o, days) {
// keep in mind, months in javascript are 0-11
return new Date(o.getFullYear(), o.getMonth(), o.getDate() - days);;
}

This is what I would do. Note you can simplify the expression, I've just written it out to make it clear you are multiplying the number of days by the number of milliseconds in a day.

 var newDate = new Date( yourDate.getTime() - (days * 24 * 60 * 60 * 1000) );

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