// 前导0
function padLeftZero(str) {
return (`00${str}`).substring(str.length)
}
/**
* 日期格式化为本地日期
* @param {str} time 时间戳
* @param {str} fmt 格式
* @return {str} 格式后日期
*/
export const formatDate = (time, fmt) => {
const date = new Date(time);
const yearReg = /(y+)/;
if (yearReg.test(fmt)) {
const [year] = fmt.match(yearReg);
fmt = fmt.replace(
year,
(`${date.getFullYear()}`).substring(4 - year.length)
)
}
const o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'H+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
}
for (const k in o) {
const reg = new RegExp(`(${k})`);
if (reg.test(fmt)) {
const [str] = fmt.match(reg);
fmt = fmt.replace(
str,
str.length === 1 ? `${o[k]}` : padLeftZero(`${o[k]}`)
)
}
}
return fmt
}
时间戳格式化成字符串
于 2021-01-21 00:30:09 首次发布