当前位置: 移动技术网 > IT编程>开发语言>JavaScript > js指定日期增加指定月份的实现方法

js指定日期增加指定月份的实现方法

2019年01月04日  | 移动技术网IT编程  | 我要评论

前言

本文主要给大家介绍的是关于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;
 };

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网