项目里遇到需要js计算日期加上月份后的日期,网上找了半天,全都不能用,于是自己写了一个,方法很简单,如果你有更好的方法,欢迎赐教,减去月份就大致一样了,就不写,这里只写一个加上月份吧。
function AddMouth(date, num)
{
//date为格式化后的日期字符yyyy-MM-dd,num为增加的月份
var monthnum = parseInt(num);
var year = parseInt(date.substring(0, 4));
var month = parseInt(date.substring(5, 7));
var day = parseInt(date.substring(8, 10));
if (month + monthnum > 12)
{
var newyear = year + 1;
var newmonth = month + monthnum - 12;
var newday = day;
}
else
{
var newyear = year
var newmonth = month + monthnum;
var newday = day;
}
var newdate = newyear + "-" + newmonth + "-" + newday;
return newdate;
}
评论区