js/javascript获取时间戳的5种方法

以下便是干货

1.获取时间戳精确到秒,13位

const timestamp = Date.parse(new Date());
console.log(timestamp);
 
//输出 1591669256000   13位

2.获取时间戳精确到毫秒,13位

const timestamp = Math.round(new Date());
console.log(timestamp);
 
//输出 1591669961203   13位

3.获取时间戳精确到毫秒,13位

const timestamp = (new Date()).valueOf();
console.log(timestamp);
 
//输出 1591670037603   13位

4.获取时间戳精确到毫秒,13位

const timestamp = new Date().getTime();
console.log(timestamp);
 
//输出 1591670068833   13位

5.获取时间戳精确到毫秒,13位

const timestamp = +new Date();
console.log(timestamp);
 
//输出 1591670099066   13位

其它

在开发的中需要精确到秒的时候,推荐使用 第1种方法,也需要除以1000才行,如果是需要时间戳毫秒的推荐 +new Date() 和 new Date().getTime();

猜你喜欢

转载自blog.csdn.net/xybhua/article/details/128661280