国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

js指定日期增加指定月份的實現方法

2019-11-19 12:19:56
字體:
來源:轉載
供稿:網友

前言

本文主要給大家介紹的是關于js實現指定日期增加指定月份的相關內容,分享出來供大家參考學習,下面話不多說了,來一起看看詳細的介紹吧

首先,大致思路為:

     1. 先將字符串格式的時間類型轉化為Date類型

     2. 再將Date類型的時間增加指定月份

     3. 最后將Date類型的時間在轉化為字符串類型

示例代碼:

1. 先將字符串格式的時間類型轉化為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類型的時間在轉化為字符串類型

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; };

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對武林網的支持。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 义马市| 夹江县| 青川县| 武夷山市| 北碚区| 综艺| 炉霍县| 如皋市| 三门县| 阜新市| 岑巩县| 古丈县| 门源| 孟津县| 临泽县| 安龙县| 兴山县| 陆河县| 长武县| 山阳县| 元阳县| 广宗县| 宁南县| 松江区| 巴彦县| 罗平县| 安庆市| 太康县| 永年县| 平乐县| 钟山县| 孝义市| 辉南县| 芦溪县| 武宁县| 湟源县| 九龙城区| 茶陵县| 龙里县| 尼玛县| 宁陕县|