`
carge
  • 浏览: 50075 次
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

JavaScript中计算下一个月的今天

阅读更多

 

     由于产品要求比较特殊,就自己做了一个日历。在2014.10.31日发现,计算下一个月的今天时候出问题了。有问题的代码如下:

 

var today = new Date();
today.setMonth(today.getMonth() + 1);
var nextMonthToday = today;

 

nextMonthToday 为 Mon Dec 01 2014 22:33:03 GMT+0800 (中国标准时间)

 

 

     究其原因发现在执行today.setMonth里面的 + 1,实际是按照当月的天数计算的。

     即在today的unix时间戳上加了31天,所以就到了12月1号。

 

     解决办法:

var date = today.getDate(); //记住当前日期
 today.setDate(1); //设置为本月1号
 today.setMonth(today.getMonth() + n); //n个月以后1号
 today.setDate(Math.min(date, getDaysInMonth(today))); // getDaysInMonth(today)表示计算下n个月当月的天数,如10月31号的下一个对应日期为11月30号

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics