首先,大致思路為:
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 };