Subtract days, months, years from a date in JavaScript

前端 未结 8 577
慢半拍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.

提交回复
热议问题