JavaScript 简洁明了的时间戳,日期格式相互转换

//将时间戳转换为yyyy-MM-dd h:m:s时间格式
function timestampToTime( timestamp) { //精确到秒
let date = new Date(timestamp);
let Y, M, D, h, m, s;
Y = date. getFullYear() + '-';
M = (date. getMonth() + 1 < 10 ? '0' +(date. getMonth() + 1) : date. getMonth() + 1) + '-';
D = (date. getDate() < 10 ? '0' +date. getDate() : date. getDate()) + ' ';
h = (date. getHours() < 10 ? '0' +date. getHours() : date. getHours()) + ':';
m = (date. getMinutes() < 10 ? '0' +date. getMinutes() : date. getMinutes()) + ':';
s = date. getSeconds() < 10 ? '0' +date. getSeconds() : date. getSeconds();
return Y +M +D +h +m +s;
}
console. log( timestampToTime( 1527040225000)); //2018-05-23 09:50:25

//将yyyy-MM-dd h:m:s时间格式转换为时间戳
function timeToTimestamp( string){
let d = new Date(string);
return d. getTime();
}
console. log( timeToTimestamp( "2018-05-23 09:50:25")); //1527040225000

猜你喜欢

转载自blog.csdn.net/w845386392/article/details/80415196