最近在做项目性能优化的时候,发现项目中关于时间的相关处理用了moment.js,但是其实只用到了两个函数,一个是时间格式转换,还有一个是时间天数+1这两个功能函数,由此引入moment.js包较为浪费打包资源,所以打算单独写一下这两个函数的处理工具类。 这里参考了网上的常用方法: 首先是时间格式转换:
Date.prototype.format = function(fmt) {
var o = {
"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+)/.test(fmt)) {
fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
}
for(var k in o) {
if(new RegExp("("+ k +")").test(fmt)){
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
}
}
return fmt;
}
这里使用的链式调用的方法,在Date原型上增加了一个format方法,调用方法如下:
var time1 = new Date().format("yyyy-MM-dd hh:mm:ss");\
console.log(time1);
//2012-12-25
var oldTime = (new Date("2012/12/25 20:11:11")).getTime();
console.log(new Date("2012/12/25 20:11:11"))
//Tue Dec 25 2012 20:11:11 GMT+0800 (中国标准时间)
//.getTime()将Date类型转换为时间戳
var curTime = new Date(oldTime).format("yyyy-MM-dd");
console.log(curTime);
//2012-12-25
然后是日期加n天的函数,也是直接通过prototype方法添加到Date类型的原型上,通过链式方式调用
Date.prototype.add = function(num) {
console.log(this.getDate())
let dateTime=new Date(this);
return new Date(dateTime.setDate(this.getDate()+num))
}
调用方法如下:
var currDate=new Date("Sat Oct 02 2021 16:22:59 GMT+0800")
console.log(currDate.add(1).format("yyyy-MM-dd hh:mm:ss"))
// 2021-10-03 16:22:59
console.log(currDate.format("MM-dd"))
// 10-02
这种方法是在Date原型上添加新的方法,但是这种方法会导致Date类型的原有数据结构被破坏,而且在ts环境下,同时需要为Date类型添加类型定义接口等,在需求不是很复杂的情况下,这种方法比较冗余,所以后续将方法改成了函数式调用,将date数据作为参数传入函数即可。