我正在寻找最简单、最干净的方法将X个月添加到JavaScript日期中。
我宁愿不处理一年的滚动,也不愿意自己写函数。
有什么内置的东西可以做到这一点吗?
我正在寻找最简单、最干净的方法将X个月添加到JavaScript日期中。
我宁愿不处理一年的滚动,也不愿意自己写函数。
有什么内置的东西可以做到这一点吗?
当前回答
我改变了一点接受的答案,以保持原始日期完整,因为我认为它应该在这样的函数中。
函数添加月份(日期,月份) { 让新日期 = 新日期(日期); var day = newdate.getDate(); newDate.setMonth(newDate.getMonth() + +months); if (newDate.getDate() != day) newDate.setDate(0); 返回新日期; }
其他回答
d = new Date();
alert(d.getMonth()+1);
月份有一个基于0的指数,它应该警报(4),这是5(五月);
var a=new Date();
a.setDate(a.getDate()+5);
如上所述的方法,您可以添加月到日期功能。
有时有用的创建日期由一个操作符,如在BIRT参数
我在1个月前用:
new Date(new Date().setMonth(new Date().getMonth()-1));
只是在已接受的答案和评论上加上一点。
var x = 12; //or whatever offset
var CurrentDate = new Date();
//For the very rare cases like the end of a month
//eg. May 30th - 3 months will give you March instead of February
var date = CurrentDate.getDate();
CurrentDate.setDate(1);
CurrentDate.setMonth(CurrentDate.getMonth()+X);
CurrentDate.setDate(date);
我写了另一种解决方案,对我来说很好。当您希望计算合同的结束时,它很有用。例如,start=2016-01-15, months=6, end=2016-7-14(即最后一天-1):
<script>
function daysInMonth(year, month)
{
return new Date(year, month + 1, 0).getDate();
}
function addMonths(date, months)
{
var target_month = date.getMonth() + months;
var year = date.getFullYear() + parseInt(target_month / 12);
var month = target_month % 12;
var day = date.getDate();
var last_day = daysInMonth(year, month);
if (day > last_day)
{
day = last_day;
}
var new_date = new Date(year, month, day);
return new_date;
}
var endDate = addMonths(startDate, months);
</script>
例子:
addMonths(new Date("2016-01-01"), 1); // 2016-01-31
addMonths(new Date("2016-01-01"), 2); // 2016-02-29 (2016 is a leap year)
addMonths(new Date("2016-01-01"), 13); // 2017-01-31
addMonths(new Date("2016-01-01"), 14); // 2017-02-28