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

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.


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()
    );
}

Never go for this solution yourDate.setDate(yourDate.getDate() - daysToSubtract);

it wont work in case your date is 1st of any month and you want to delete some days say 1.

Instead go for below solution which will work always

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


Here i am posting one more answer and that will return date in specific format.

First you can get current date 10/08/2013 as below

function Cureent_Date() {
    var today_GMT = new Date();
    var dd = today_GMT.getDate();
    var mm = today_GMT.getMonth() + 1; //January is 0!
    var yyyy = today_GMT.getFullYear();
    if (dd < 10) {
        dd = '0' + dd
    }
    if (mm < 10) {
        mm = '0' + mm
    }
    current_date = mm + '/' + dd + '/' + yyyy;
    alert("current_date"+current_date);

    Back_date();
}

Now Get back date base on X days

function Back_date()
{    
    var back_GTM = new Date(); back_GTM.setDate(back_GTM.getDate() - 2); // 2 is your X
    var b_dd = back_GTM.getDate();
    var b_mm = back_GTM.getMonth()+1;
    var b_yyyy = back_GTM.getFullYear();
    if (b_dd < 10) {
        b_dd = '0' + b_dd
    }
    if (b_mm < 10) {
        b_mm = '0' +b_mm
    }

    var back_date=  b_mm + '/' + b_dd + '/' + b_yyyy;
    alert("back_date"+back_date);
}

So, Today is 10/08/2013 so it will return 10/06/2013.

Check Live Demo here Hope this answer will help you.


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