工作中经常会用到处理日期的方法,为了使更便捷,把日期时间统一做了一下处理。 上代码
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.ceil((this.getMonth() + 1) / 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的方法,接收一个参数fmt,这个fmt就是我们需要传入的日期时间格式,比如'yyyy-MM-dd hh:mm:ss';
首先是一个对象o, 里面是月、日、时、分、秒、季度、毫秒这些属性对应的具体值;this指向日期实例。
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
}
这一句啥意思呢?/(y+)/是一个正则表达式,/(y+)/.test(fmt)判断fmt里面是否含有年份y,有则根据y的个数来显示年份;
RegExp.$1指的又是啥?指的是正则里面第一个小括号匹配到fmt中的值,yyyy。
String.substr()方法,详见String.substr();
剩下的就是循环替换了。
实例:
new Date().format('yyyy MM月dd日 hh:mm S 第q季度') = > 2020 11月01日 23:57 948 第4季度