js指定日期增加指定月份的实现方法
网络编程 2021-07-04 16:47www.168986.cn编程入门
这篇文章主要给大家介绍了关于js指定日期增加指定月份的实现方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们狼蚁网站SEO优化来一起学习学习吧
前言
本文主要给大家介绍的是关于js实现指定日期增加指定月份的相关内容,分享出来供大家参考学习,狼蚁网站SEO优化话不多说了,来一起看看详细的介绍吧
,大致思路为
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; };
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对狼蚁SEO的支持。
编程语言
- 宿迁百度关键词排名指南:实现精准营销的关键
- 四川SEO优化怎么做网络推广
- 立昂技术备案老域名收购:如何为您的业务赋能
- 安徽百度关键词seo贵不贵,一般需要多少钱
- 吉林百度快照排名怎么做电话营销
- 多伦新手做SEO怎么做
- 甘肃优化关键词排名推广怎么做论坛营销
- 沙雅SEO网站推广:提升您的在线可见性
- 四川SEO优化如何提升销售额和销售量
- 聂荣网站排名优化:提升网站可见性的全方位指
- 涞水SEO:提升地方企业在线可见性的策略
- 辽宁百度seo排名怎样做网站排名
- 临湘哪有关键词排名优化:提升网站可见度的关
- 黑龙江百度网站优化有没有优惠
- 凉城优化关键词排名推广:提升您的网络可见性
- 萝北整站优化:提升您网站流量和排名的全面指