时间的操作是一个很常见的操作,有时候要展示成“2021-01-11”,“2021年01月11日”…每一次都需要写一遍代码,感觉很浪费时间,所以今天打算封装一个公共的方法,以便以后使用,在菜鸟教程查看Date相关api时,看见了一篇笔记,使我受益匪浅。向作者致谢。。
进入正文
开始封装
Date.prototype.format = function (fmt) {
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"min+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"ms": this.getMilliseconds() //毫秒
};
// 获取年份
if (/(y+)/i.test(fmt)) {
// RegExp.$1是RegExp的一个属性,指的是与正则表达式匹配的第一个 子匹配(以括号为标志)字符串
// RegExp.$1 匹配到的是yyyy
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp("(" + k + ")", "i").test(fmt)) {
fmt = fmt.replace(
RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
}
return fmt;
}
调用方式
var now = new Date();
var nowStr = now.format("YYYY-MM-DD"); // 2021-01-11
var now1Str = now.format("YYYY年MM月DD日 hh时min分ss秒");// 2021年01月11日 11时44分35秒