JS获取时间戳的5种方法
在JavaScript中,获取时间戳(从1970年1月1日00:00:00 UTC到现在的毫秒数)有以下5种常用方法:
1. Date.now() (推荐)
const timestamp = Date.now();
console.log(timestamp); // 例如:1698765432100
特点:
- 最简单直接的方法
- ES5引入,性能
- 不创建Date对象
2. new Date().getTime()
const timestamp = new Date().getTime();
console.log(timestamp);
特点:
- 兼容性好,所有浏览器都支持
- 需要创建Date对象
3. +new Date() (一元操作符)
const timestamp = +new Date();
console.log(timestamp);
特点:
- 利用一元+操作符将Date对象转换为数字
- 代码简洁但可读性稍差
4. new Date().valueOf()
const timestamp = new Date().valueOf();
console.log(timestamp);
特点:
- 调用Date对象的valueOf方法
- 与getTime()效果相同
5. Date.parse(new Date())
const timestamp = Date.parse(new Date());
console.log(timestamp);
特点:
- 精度只到秒级(后三位为000)
- 不推荐用于需要精确毫秒的场景
注意事项
- 前4种方法获取的是毫秒级时间戳,第5种是秒级(后三位补零)
- 在性能敏感场景推荐使用
Date.now()
- 如果需要秒级时间戳,可以
Math.floor(Date.now() / 1000)
- 时间戳在JavaScript中是UTC时间,不受本地时区影响