How to determine one year from now in Javascript

后端 未结 8 1205
醉话见心
醉话见心 2020-12-12 21:29

I\'m trying to get one year from now\'s date, and it\'s not working.

JS:

var now = new Date();

var oneYr = new Date();
oneYr.setYear(now.getYear() +         


        
相关标签:
8条回答
  • 2020-12-12 21:53

    Use setFullyear as others have posted but be aware this returns a timestamp value not a date object. It is also a good candidate imho to add functionality via the prototype. This leads us to the following pattern:

    Date.prototype.addYears = function(n) {
        var now = new Date();
        return new Date(now.setFullYear(now.getFullYear() + n));
    };
    
    console.log('Year from now is', new Date().addYears(1));
    
    0 讨论(0)
  • 2020-12-12 21:57

    2020

    It's perfect date/time library called Moment.js with this library you can simply write:

    moment().subtract(1,'year')
    

    and call any format you wish:

    moment().subtract(1,'year').toDate()
    moment().subtract(1,'year').toISOString()
    

    See full documentation here: https://momentjs.com/

    0 讨论(0)
  • 2020-12-12 21:59

    This will create a Date exactly one year in the future with just one line. First we get the fullYear from a new Date, increment it, set that as the year of a new Date. You might think we'd be done there, but if we stopped it would return a timestamp, not a Date object so we wrap the whole thing in a Date constructor.

    new Date(new Date().setFullYear(new Date().getFullYear() + 1))
    
    0 讨论(0)
  • 2020-12-12 22:07

    As setYear() is deprecated, correct variant is:

    // plus 1 year
    new Date().setFullYear(new Date().getFullYear() + 1)
    // plus 1 month
    new Date().setMonth(new Date().getMonth() + 1)
    // plus 1 day
    new Date().setDate(new Date().getDate() + 1)
    

    All examples return Unix timestamp, if you want to get Date object - just wrap it with another new Date(...)

    0 讨论(0)
  • 2020-12-12 22:08

    Using some of the answers on this page and here, I came up with my own answer as none of these answers fully solved it for me.

    Here is crux of it

    var startDate = "27 Apr 2017";
    var numOfYears = 1;
    var expireDate = new Date(startDate);
    expireDate.setFullYear(expireDate.getFullYear() + numOfYears);
    expireDate.setDate(expireDate.getDate() -1);
    

    And here a a JSFiddle that has a working example: https://jsfiddle.net/wavesailor/g9a6qqq5/

    0 讨论(0)
  • 2020-12-12 22:09

    Use this:

    var startDate = new Date();
        startDate.setFullYear(startDate.getFullYear() - 1);
    
    0 讨论(0)
提交回复
热议问题