方式一:
_formatDate(format, time) {
let date = time ? new Date(time) : new Date();
let regexps = ['(Y{1,4})', '(M{1,2})', '(D{1,2})', '(h{1,2})', '(m{1,2})', '(s{1,2})', '(S{1,3})'];
let fns = ['FullYear', 'Month', 'Date', 'Hours', 'Minutes', 'Seconds', 'Milliseconds'];
let dateStr = format;
for (let i = 0; i < regexps.length; i++) {
let r = new RegExp(regexps[i]);
if (r.test(format)) {
let val = `${date[`get${fns[i]}`]() + (i === 1 ? 1 : 0)}`;
if (val.length > RegExp.$1.length) {
val = val.substr(val.length - RegExp.$1.length);
}
if (val.length < RegExp.$1.length) {
let zeros = new Array(RegExp.$1.length - val.length).fill('0');
val = zeros.join('') + val;
}
dateStr = dateStr.replace(RegExp.$1, val);
}
}
return dateStr;
}
方式二:
Date.prototype.format = function () {
//下列参数可能的值:"numeric","2-digit","narrow","short","long"
return this.toLocaleDateString(undefined, {
timeZone: 'Asia/Shanghai',
hour12: false,
// weekday : 'short',
// era : 'short',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: "2-digit",
minute: "2-digit",
second: "2-digit"
});
};