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

我宁愿不处理一年的滚动,也不愿意自己写函数。

有什么内置的东西可以做到这一点吗?


当前回答

只是在已接受的答案和评论上加上一点。

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);

其他回答

我改变了一点接受的答案,以保持原始日期完整,因为我认为它应该在这样的函数中。

函数添加月份(日期,月份) { 让新日期 = 新日期(日期); var day = newdate.getDate(); newDate.setMonth(newDate.getMonth() + +months); if (newDate.getDate() != day) newDate.setDate(0); 返回新日期; }

在typescript中寻找一些东西?

export const addMonths = (inputDate: Date | string, monthsToAdd: number): Date => {
  const date = new Date(inputDate);
  if (!monthsToAdd) {
    return date;
  }
  const dayOfMonth = date.getDate(); 
  const endOfDesiredMonth = new Date(date.getTime());
  endOfDesiredMonth.setMonth(date.getMonth() + monthsToAdd + 1, 0);
  const daysInMonth = endOfDesiredMonth.getDate();
  if (dayOfMonth >= daysInMonth) {
    return endOfDesiredMonth;
  } else {
    date.setFullYear(endOfDesiredMonth.getFullYear(), endOfDesiredMonth.getMonth(), dayOfMonth);
    return date;
  }
}

只是在已接受的答案和评论上加上一点。

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);
var a=new Date();
a.setDate(a.getDate()+5);

如上所述的方法,您可以添加月到日期功能。

正如大多数答案突出显示的那样,我们可以使用setMonth()方法和getMonth()方法一起为给定的日期添加特定的月份数。

例子:(@ChadD在他的回答中提到。)

Var x = 12;//或任何偏移量 var CurrentDate = new Date(); CurrentDate.setMonth(CurrentDate.getMonth() + x);

但是我们应该小心地使用这个解决方案,因为我们会在边界情况下遇到麻烦。

要处理边缘情况,下面链接中给出的答案是有帮助的。 https://stackoverflow.com/a/13633692/3668866