下面是一个将时间毫秒数转换为指定日期格式的JavaScript函数:
function formatDate(ms, format = 'YYYY-MM-DD hh:mm:ss') {
const date = new Date(ms);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
const map = {
'YYYY': year,
'MM': addPrefixZero(month),
'M': month,
'DD': addPrefixZero(day),
'D': day,
'hh': addPrefixZero(hours),
'h': hours,
'mm': addPrefixZero(minutes),
'm': minutes,
'ss': addPrefixZero(seconds),
's': seconds,
};
let result = format;
for (const key in map) {
result = result.replace(key, map[key]);
}
return result;
}
// 在个位数字前面添加 0,使得数字位数为两位
function addPrefixZero(num) {
return num < 10 ? '0' + num : num;
}
函数接受两个参数,第一个参数ms是时间戳的毫秒数,第二个参数format是指定的日期时间格式,默认为'YYYY-MM-DD hh:mm:ss',即年月日时分秒。
函数中首先创建一个Date对象,然后使用getFullYear()、getMonth()、getDate()、getHours()、getMinutes()、getSeconds()等方法获取年月日时分秒。接着创建一个对象map,该对象的属性是日期时间格式中的占位符,值是对应的时间值。然后遍历map对象,将日期时间格式中的占位符替换成对应的时间值。最后返回替换完成后的日期时间字符串。
例如,如果想要将时间戳1623617719256转换为YYYY-MM-DD hh:mm:ss格式的日期时间字符串,可以这样写:
const ms = 1623617719256;
const format = 'YYYY-MM-DD hh:mm:ss';
const result = formatDate(ms, format);
console.log(result); // 2021-06-14 04:55:19