How to determine one year from now in Javascript

后端 未结 8 1211
醉话见心
醉话见心 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 22:14

    You should use getFullYear() instead of getYear(). getYear() returns the actual year minus 1900 (and so is fairly useless).

    Thus a date marking exactly one year from the present moment would be:

    var oneYearFromNow = new Date();
    oneYearFromNow.setFullYear(oneYearFromNow.getFullYear() + 1);
    

    Note that the date will be adjusted if you do that on February 29.

    Similarly, you can get a date that's a month from now via getMonth() and setMonth(). You don't have to worry about "rolling over" from the current year into the next year if you do it in December; the date will be adjusted automatically. Same goes for day-of-month via getDate() and setDate().

提交回复
热议问题