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) { 4var y = this.getFullYear(); 5var m = this.getMonth(); 6var nextY = y; 7var nextM = m; 8//如果當前月+要加上的月>11 這裡之所以用11是因為 js的月份從0開始 9if ((m + addMonth)> 11) { 10nextY = y + 1; 11nextM = parseInt(m + addMonth) - 12; 12} else { 13nextM = this.getMonth() + addMonth 14} 15var daysInNextMonth = Date.daysInMonth(nextY, nextM); 16var day = this.getDate(); 17if (day > daysInNextMonth) { 18day = daysInNextMonth; 19} 20return new Date(nextY, nextM, day); 21}; 22Date.daysInMonth = function (year, month) { 23if (month == 1) { 24if (year % 4 == 0 && year % 100 != 0) 25return 29; 26else 27return 28; 28} else if ((month <= 6 && month % 2 == 0) || (month = 6 && month % 2 == 1)) 29return 31; 30else 31return 30; 32}; View Code
3. 最後將Date型別的時間在轉化為字串型別
1 var nowStr = nowDate.format('yyyy-MM-dd hh:mm:ss');//指定字串格式的時間型別 2 3 Date.prototype.format = function (format) { 4var 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}; 13if (/(y+)/i.test(format)) { 14format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length)); 15} 16for (var k in date) { 17if (new RegExp("(" + k + ")").test(format)) { 18format = format.replace(RegExp.$1, RegExp.$1.length == 1 19? date[k] : ("00" + date[k]).substr(("" + date[k]).length)); 20} 21} 22return format; 23}; View Code