本文详细介绍在JavaScript中如何将字符串格式的日期转换为Date对象,通过扩展Date原型实现指定月份的增加,最后再转换回字符串格式。文章提供了完整的代码示例和关键逻辑解析,帮助开发者快速掌握日期加减月份的操作方法。
JavaScript实现指定日期增加指定月份的方法
前言
本文主要介绍在JavaScript中实现指定日期增加指定月份的功能,分享相关代码供参考学习。
实现思路大致如下:
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;
};
总结
以上就是JavaScript实现指定日期增加指定月份的完整内容,希望本文对大家的学习或工作有所帮助。如有疑问,欢迎留言交流,感谢支持。