// 时间转换timestamp为numebr,单位毫秒,format为格式,是一个字符串
function timestampToTime(timestamp, format) {
var date = new Date(timestamp);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
var Y = date.getFullYear();
var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
var D = date.getDate();
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
var yReg = /yyyy/;
var mReg1 = /MM/;
var dReg = /DD/;
var hReg = /HH/;
var mReg = /mm/;
var sReg = /SS/;
return format.replace(yReg, Y).replace(mReg1, M).replace(dReg, D).replace(hReg, h).replace(mReg, m).replace(sReg, s);
}
var date = new Date();
var format = 'yyyy年MM月DD日HH:mm:SS';
console.log(timestampToTime(date, format));
上面方法结果:将当前时间戳 1607593148941 转为 日期格式 2022年09月14日21:20:41

该博客介绍了一个JavaScript函数,用于将时间戳转换为指定格式的日期字符串。通过使用Date对象和正则表达式,该函数能够将当前时间戳(例如1607593148941)转化为'2022年09月14日21:20:41'这样的日期格式。
948

被折叠的 条评论
为什么被折叠?



