Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

javascript - 用于将X月添加到日期的JavaScript函数(JavaScript function to add X months to a date)

I'm looking for the easiest, cleanest way to add X months to a JavaScript date.

(我正在寻找将X个月添加到JavaScript日期的最简单,最干净的方法。)

I'd rather not handle the rolling over of the year or have to write my own function .

(我宁愿不处理今年的滚动或者必须编写我自己的功能 。)

Is there something built in that can do this?

(有内置的东西能做到吗?)

  ask by ChadD translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think this should do it:

(我认为应该这样做:)

 var x = 12; //or whatever offset var CurrentDate = new Date(); console.log("Current date:", CurrentDate); CurrentDate.setMonth(CurrentDate.getMonth() + x); console.log("Date after " + x + " months:", CurrentDate); 

I believe it should automatically handle incrementing to the appropriate year and mod-ing to the appropriate month.

(我相信它应该自动处理递增到适当的年份并修改到适当的月份。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...