How to determine one year from now in Javascript

后端 未结 8 1207
醉话见心
醉话见心 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));
    

提交回复
热议问题