Date 对象的 format 扩展
题目:扩展 Date 原型,传入
format模板字符串渲染成yyyy-MM-dd hh:mm:ss等格式。
Date.prototype.format = function (format) {
var args = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3), //quarter
"S": this.getMilliseconds()
};
if (/(y+)/.test(format))
format = format.replace(RegExp.$1, (this.getFullYear() + "")
.substr(4 - RegExp.$1.length));
for (var i in args) {
var n = args[i];
if (new RegExp("(" + i + ")").test(format))
format = format.replace(RegExp.$1, RegExp.$1.length == 1
? n
: ("00" + n).substr(("" + n).length));
}
return format;
};
alert(new Date("Sun May 27 2018 09:08:09 GMT+0800").format("yyyy-MM-dd hh:mm:ss"));
补充
补充:原笔记里
alert(...)后又冒出一行-mm-dd hh:MM:ss等格式字符串跑到围栏外,导致 markdown 解析混乱。已把它整理进代码块。模板支持的占位符:
yyyy(4 位年)、MM(2 位月)、dd(2 位日)、hh/HH(12/24 小时)、mm(分钟)、ss(秒)、q(季度)、S(毫秒)。



