js指定日期增加指定月份的實現(xiàn)方法
前言
本文主要給大家介紹的是關(guān)于js實現(xiàn)指定日期增加指定月份的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),下面話不多說了,來一起看看詳細的介紹吧
首先,大致思路為:
1. 先將字符串格式的時間類型轉(zhuǎn)化為Date類型
2. 再將Date類型的時間增加指定月份
3. 最后將Date類型的時間在轉(zhuǎn)化為字符串類型
示例代碼:
1. 先將字符串格式的時間類型轉(zhuǎn)化為Date類型
var str = '2018-01-01 00:00:00'; //字符串格式的時間類型 var str1 = str.replace(/-/g,'/'); //'2018/01/01 00:00:00' var date = new Date(Date.parse(str1)); //date格式的時間類型
2. 再將Date類型的時間增加指定月份
var nowDate = date.addMonth(3); //date格式的時間類型 Date.prototype.addMonth = function (addMonth) { var y = this.getFullYear(); var m = this.getMonth(); var nextY = y; var nextM = m; //如果當前月+要加上的月>11 這里之所以用11是因為 js的月份從0開始 if ((m + addMonth)> 11) { nextY = y + 1; nextM = parseInt(m + addMonth) - 12; } else { nextM = this.getMonth() + addMonth } var daysInNextMonth = Date.daysInMonth(nextY, nextM); var day = this.getDate(); if (day > daysInNextMonth) { day = daysInNextMonth; } return new Date(nextY, nextM, day); }; Date.daysInMonth = function (year, month) { if (month == 1) { if (year % 4 == 0 && year % 100 != 0) return 29; else return 28; } else if ((month <= 6 && month % 2 == 0) || (month = 6 && month % 2 == 1)) return 31; else return 30; };
3. 最后將Date類型的時間在轉(zhuǎn)化為字符串類型
var nowStr = nowDate.format('yyyy-MM-dd hh:mm:ss'); //指定字符串格式的時間類型 Date.prototype.format = function (format) { var date = { "M+": this.getMonth() + 1, "d+": this.getDate(), "h+": this.getHours(), "m+": this.getMinutes(), "s+": this.getSeconds(), "q+": Math.floor((this.getMonth() + 3) / 3), "S+": this.getMilliseconds() }; if (/(y+)/i.test(format)) { format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length)); } for (var k in date) { if (new RegExp("(" + k + ")").test(format)) { format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k] : ("00" + date[k]).substr(("" + date[k]).length)); } } return format; };
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
JavaScript Object的extend是一個常用的功能
對Object的extend是一個常用的功能。舉一個例子,由于javascript 沒有重載(overload),而且函數(shù)的參數(shù)類型是沒有定義的,所以很多時候我們都傳入一個對象來作為參數(shù)已方便控制。2009-12-12javascript自執(zhí)行函數(shù)之偽命名空間封裝法
比較之后,我們可以發(fā)現(xiàn),第二方法更加的直觀,易于理解。但是少了封裝過程,代碼完全裸露在外。2010-12-12JavaScript打印網(wǎng)頁指定區(qū)域的例子
這篇文章主要介紹了JavaScript打印網(wǎng)頁指定區(qū)域的例子,需要的朋友可以參考下2014-05-05JavaScript在網(wǎng)頁中畫圓的函數(shù)arc使用方法
這篇文章主要介紹了JavaScript在網(wǎng)頁中畫圓的函數(shù)arc使用方法的相關(guān)資料,需要的朋友可以參考下2015-11-11