因为前端展示日期的格式不是固定的,所以后端返回的时间一般都是一个时间戳(单位为ms,以1970年1月1日为起点)。
当我们想要把这个时间戳转换成一定的格式时,就需要手动封装一个格式化函数了。
先创建Date实例(乘以1000将单位转换为s):
let date = new Date(value * 1000);
然后把date以及转换的格式传给格式化函数:
formatDate(date, "yyyy-MM-dd hh:mm:ss");
格式化函数所在文件如下,包含两个函数:
export function debounce(func, delay) {
let timer = null
//若不需要参数args可忽视
return function (...args) {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
func.apply(this, args)
}, delay)
}
}
// 时间戳格式化
export function formatDate(date, fmt) {
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
}
let o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
};
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
let str = o[k] + '';
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
}
}
return fmt;
};
function padLeftZero(str) {
return ('00' + str).substr(str.length);
};