js实现指定日期增加指定月份

首先,大致思路为:

1. 先将字符串格式的时间类型转化为Date类型

2. 再将Date类型的时间增加指定月份

3. 最后将Date类型的时间在转化为字符串类型

1.  先将字符串格式的时间类型转化为Date类型

1 var str = '2018-01-01 00:00:00';   //字符串格式的时间类型
2 var str1 = str.replace(/-/g,'/');   //'2018/01/01 00:00:00'
3 var date = new Date(Date.parse(str1));   //date格式的时间类型

2. 再将Date类型的时间增加指定月份

 1 var nowDate = date.addMonth(3);   //date格式的时间类型
 2 
 3 Date.prototype.addMonth = function (addMonth) {
 4         var y = this.getFullYear();
 5         var m = this.getMonth();
 6         var nextY = y;
 7         var nextM = m;
 8         //如果当前月+增加的月>11 这里之所以用11是因为 js的月份从0开始
 9         if ((m + addMonth)> 11) {
10             nextY = y + 1;
11             nextM = parseInt(m + addMonth) - 12;
12         } else {
13             nextM = this.getMonth() + addMonth
14         }
15         var daysInNextMonth = Date.daysInMonth(nextY, nextM);
16         var day = this.getDate();
17         if (day > daysInNextMonth) {
18             day = daysInNextMonth;
19         }
20         return new Date(nextY, nextM, day);
21     };
22 
23     //计算当前月最大天数
24     Date.daysInMonth = function (year, month) {
25         if (month == 1) {
26             if (year % 4 == 0 && year % 100 != 0)
27                 return 29;
28             else
29                 return 28;
30         } else if ((month <= 6 && month % 2 == 0) || (month > 6 && month % 2 == 1))
31             return 31;
32         else
33             return 30;
34     };

3. 最后将Date类型的时间在转化为字符串类型

 1 var nowStr = nowDate.format('yyyy-MM-dd hh:mm:ss');   //指定字符串格式的时间类型
 2 
 3 Date.prototype.format = function (format) {
 4         var date = {
 5             "M+": this.getMonth() + 1,
 6             "d+": this.getDate(),
 7             "h+": this.getHours(),
 8             "m+": this.getMinutes(),
 9             "s+": this.getSeconds(),
10             "q+": Math.floor((this.getMonth() + 3) / 3),
11             "S+": this.getMilliseconds()
12         };
13         if (/(y+)/i.test(format)) {
14             format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
15         }
16         for (var k in date) {
17             if (new RegExp("(" + k + ")").test(format)) {
18                 format = format.replace(RegExp.$1, RegExp.$1.length == 1
19                     ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
20             }
21         }
22         return format;
23     };
原文地址:https://www.cnblogs.com/mengbing/p/10135497.html