Subtract days, months, years from a date in JavaScript

前端 未结 8 574
慢半拍i
慢半拍i 2020-12-13 03:32

Does anybody know of a simple way of taking a date (e.g. Today) and going back X days, X months and X years?

I have tried that:

var date = new Date()         


        
相关标签:
8条回答
  • 2020-12-13 04:02

    I'd recommend using the MomentJS libraries. They make all interactions with Dates a lot simpler.

    If you use Moment, your code would be as simple as this:

    var today = moment();
    var nextMonth = today.add('month', 1);
    // note that both variables `today` and `nextMonth` refer to 
    // the next month at this point, because `add` mutates in-place
    

    You can find MomentJS here: http://momentjs.com/

    UPDATE:

    In JavaScript, the Date.getDate() function returns the current day of the month from 1-31. You are subtracting 6 from this number, and it is currently the 3rd of the month. This brings the value to -3.

    0 讨论(0)
  • 2020-12-13 04:09

    This does not answer the question fully, but for anyone who is able to calculate the number of days by which they would like to offset an initial date then the following method will work:

    myDate.setUTCDate(myDate.getUTCDate() + offsetDays);
    

    offsetDays can be positive or negative and the result will be correct for any given initial date with any given offset.

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