时间戳转日期格式字符串
/**
* @param {string} timestamp
* @param {string || null} fmt
* @returns {String}
*/
function timeFormat(timestamp = null, fmt = "yyyy-mm-dd") {
if (timestamp == null) timestamp = +new Date();
if (timestamp.toString().length == 10) timestamp *= 1000;
let date = new Date(timestamp);
let ret;
let opt = {
"y+": date.getFullYear().toString(), // 年
"m+": (date.getMonth() + 1).toString(), // 月
"d+": date.getDate().toString(), // 日
"h+": date.getHours().toString(), // 时
"M+": date.getMinutes().toString(), // 分
"s+": date.getSeconds().toString() // 秒
};
for (let k in opt) {
ret = new RegExp("(" + k + ")").exec(fmt);
if (ret) {
fmt = fmt.replace(
ret[1],
ret[1].length == 1
? opt[k]
: opt[k].padStart(ret[1].length, "0")
);
}
}
return fmt;
}
效果:
console.log(timeFormat(null,'yyyy/mm/dd hh:MM:ss'))
//打印结果: 2021/12/23 17:14:02
console.log(timeFormat(null,'yy/mm/dd hh:MM'))
//打印结果:2021/12/23 17:14