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

后端 未结 9 1927
滥情空心
滥情空心 2020-11-27 05:21

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 i

相关标签:
9条回答
  • 2020-11-27 06:13

    Simply:

    yourDate.setDate(yourDate.getDate() - daysToSubtract);
    
    0 讨论(0)
  • 2020-11-27 06:19

    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.

    0 讨论(0)
  • 2020-11-27 06:19

    Just another option, which I wrote:

    DP_DateExtensions Library

    It's probably overkill if ALL you want to do is one calculation, but if you're going to do more date manipulation you might find it useful.

    Supports date/time formatting, date math (add/subtract date parts), date compare, date parsing, etc.

    0 讨论(0)
提交回复
热议问题