广告位联系
返回顶部
分享到

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

JavaScript 来源:转载 作者:秩名 发布时间:2018-12-19 19:48:53 人浏览
摘要

本篇文章介绍js实现指定日期增加指定月份的方法。 首先,大致思路为: 1. 先将字符串格式的时间类型转化为Date类型 2. 再将Date类型的时间增加指定月份 3. 最后将Date类型的时间在转化为字符串类型 示例代码: 1. 先将字符串格式的时间类型转化为Date类型 va

本篇文章介绍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;
 };



版权声明 : 本文内容来源于互联网或用户自行发布贡献,该文观点仅代表原作者本人。本站仅提供信息存储空间服务和不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权, 违法违规的内容, 请发送邮件至2530232025#qq.cn(#换@)举报,一经查实,本站将立刻删除。
原文链接 :
相关文章
  • 本站所有内容来源于互联网或用户自行发布,本站仅提供信息存储空间服务,不拥有版权,不承担法律责任。如有侵犯您的权益,请您联系站长处理!
  • Copyright © 2017-2022 F11.CN All Rights Reserved. F11站长开发者网 版权所有 | 苏ICP备2022031554号-1 | 51LA统计