const isDate = obj => obj instanceof Date
export default function(oDate, sFormation) {
if (!isDate(oDate)) {
oDate = new Date(oDate)
}
if (!isDate(oDate)) {
throw new Error('can not format first param to Date')
}
const obj = {
yyyyyyyy:oDate.getFullYear(),
yy:oDate.getFullYear(),
MM:oDate.getMonth()+1,
dd:oDate.getDate(),
HH:oDate.getHours(),
hh:oDate.getHours() % 12,
mm:oDate.getMinutes(),
ss:oDate.getSeconds(),
ww:"星期"+['日', '一', '二', '三', '四', '五', '六'][oDate.getDay()]
};
return sFormation.replace(/([a-z]+)/ig, function($1) {
return obj[$1+$1] || ('0'+obj[$1]).slice(-2);
});
}
内容非原创,借鉴了牛客网某个题的回答,感觉这种思路比较优秀,也较为实用,但现在原文地址找不到了,对原作者表示抱歉!
使用示例:console.log(formatDate(new Date(),‘yyyy-MM-dd HH:mm:ss w’));