Date是前端日常开发中经常会遇到的对象,我们经常遇到的有日期格式化、加减若干天等,如果使用JS的Date对象直接进行处理的话会产生一些冗余的代码,对此我们可以针对Date对象进行一些扩展,可以更便捷的使用Date对象。
格式化日期
/**
* 格式化日期
* @param partten 日期格式
* @author haohy
*/
Date.prototype.format = function(partten){
if (partten == "") {
return this.toString();
}
var str = '';
str = partten.replace(/YYYY|yyyy/, this.getFullYear())
.replace(/MM|mm/, this.getMonth() + 1)
.replace(/DD|dd/, this.getDate())
.replace(/HH|hh/, this.getHours())
.replace(/II|ii/, this.getMinutes())
.replace(/SS|ss/, this.getSeconds());
return str;
}
调用的方式为:
new Date(1532587821000).format("YYYY-MM-DD HH:II:SS");
运行结果为:
2018-7-26 14:50:21
加减日期
/**
* 加减日期
* @param day 需要加减的日期,减日期的时候为负数即可
* @author haohy
*/
Date.prototype.addDay = function(day){
this.setDate(this.getDate() + day);
return this;
};
调用的方式为:
new Date(1532587821000).addDay(12).format("YYYY-MM-DD HH:II:SS");
运行结果为:
2018-8-7 14:50:21
加减月份
/**
* 加减日期
* @param month 需要加减的月份,减月份的时候为负数即可
* @author haohy
*/
Date.prototype.addMonth = function(month){
this.setMonth(this.getMonth() + month);
return this;
};
调用的方式为:
new Date(1532587821000).addMonth(3).format("YYYY-MM-DD HH:II:SS");
运行结果为:
2018-10-26 14:50:21
以上为针对JS中Date对象的一些扩展方法,个人见解如有不足之处,欢迎大家多多指点!
如需转载请指明出处,谢谢!