如果我的日期是2014年5月31日,那么如果我说date.setMonth(date.getMonth()+ 1)到下个月,我会在2014年7月1日到期.我希望能在2014年6月30日到我想这是因为六月没有31天,所以JavaScript最好避免错误.
我写了一个特殊的函数来实际根据计算在该日期对象上执行setDate,setMonth和setYear函数.似乎单独的setMonth没有做正确的事情.
理念,
大卫
你想从现在开始1个月吗?如果是这样,你得到的是正确的.从5月31日开始的1个月是7月1日,而不是6月30日.如果您希望它仅根据本月的天数移至第二个月:
例如:Jan 31st 2014 -> Feb 28th 2014
或者您提到的情况,您可以使用小黑客来使用当前日期的最小值和下个月的天数来保持同一个月:
// Assume its yesterday
var date = new Date(2014, 4, 31);
// Get the current date
var currentDate = date.getDate();
// Set to day 1 to avoid forward
date.setDate(1);
// Increase month by 1
date.setMonth(date.getMonth() + 1);
// Get max # of days in this new month
var daysInMonth = new Date(date.getYear(), date.getMonth()+1, 0).getDate();
// Set the date to the minimum of current date of days in month
date.setDate(Math.min(currentDate, daysInMonth));
Run Code Online (Sandbox Code Playgroud)