时间戳转时间格式函数

封装好项目需要用到时可以直接调用的函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function timestampToTime(timestamp) {
const date = new Date(timestamp * 1000); // 时间戳为10位需*1000, 时间戳为13位的话不需乘1000
const Y = date.getFullYear() + "-";
const M =
(date.getMonth() + 1 < 10
? "0" + (date.getMonth() + 1)
: date.getMonth() + 1) + "-";
const D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";

const h =
(date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
const m =
(date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
":";
const s =
date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
return Y + M + D + h + m + s;
}