---
title: "JavaScript中计算下一个月的今天"
author: "carge"
date: "2014-10-31T22:46:35Z"
tags: []
categories: ["Web前端"]
slug: "javascript"
draft: false
lastmod: "2014-10-31T22:48:15Z"
id: 2150848
url: "https://carge.iteye.com/blog/2150848"
---

由于产品要求比较特殊，就自己做了一个日历。在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号
```