const date = new Date("1992-2-12 10:22:18");
function dateFormat(date, format = "YYYY-MM-DD HH:mm:ss") {
const config = {
YYYY: date.getFullYear(),
MM: date.getMonth(),
DD: date.getDate(),
HH: date.getHours(),
mm: date.getMinutes(),
ss: date.getSeconds()
};
for (const key in config){
format = format.replace(key,config[key])
}
return format;
}
console.log(dateFormat(date,'YYYY年MM月DD日'))
tips:如果需要对不够两位数的加零,比如1992-2-12改成1992-02-12,可以直接在MM后面.toString().padStart(2,0),意思是如果字符串不够两位数,则在前面填0。
另外推荐一个第三方的格式化时间的库:http://momentjs.cn/ |