如何在Node.js中获取纳秒级当前时间?现有方法失效求替代
Node.js 获取当前时间纳秒值的可行方案
你原来的process.hrtime()函数无法满足需求的原因有两个:
- 该API返回的是相对时间(相对于进程启动或某个随机基准点),并非从1970-01-01 UTC开始的绝对时间纳秒值;
- Node.js v10.0.0起,
process.hrtime()已被标记为废弃,不再推荐使用。
以下是几种可靠的实现方式:
方法一:结合 Date.now() 与 process.hrtime.bigint()
适用于Node.js v8.5.0及以上版本,能精准计算当前绝对时间的纳秒戳:
function getCurrentNanoTimestamp() { // 先获取毫秒级绝对时间戳,转为BigInt const millisecondTimestamp = BigInt(Date.now()); // 获取进程内的纳秒级相对偏移,取毫秒内的纳秒部分 const nanoOffset = process.hrtime.bigint() % BigInt(1000000); // 转换为纳秒级绝对时间戳 return millisecondTimestamp * BigInt(1000000) + nanoOffset; }
方法二:使用 performance API
适用于Node.js v8.5.0及以上版本,同样支持纳秒级精度:
function getCurrentNanoTimestamp() { // timeOrigin是当前进程启动时的Unix毫秒时间戳 const timeOriginNs = BigInt(Math.floor(performance.timeOrigin * 1000000)); // performance.now()返回进程启动后经过的毫秒数(带小数),转为纳秒 const elapsedNs = BigInt(Math.floor(performance.now() * 1000000)); return timeOriginNs + elapsedNs; }
方法三:直接使用 BigInt 版高精度时间(Node.js v16+)
Node.js v16.0.0及以上提供了更简洁的方式:
function getCurrentNanoTimestamp() { // 获取当前时间的纳秒级BigInt值(从1970-01-01 UTC开始) return BigInt(new Date().getTime()) * BigInt(1000000) + (process.hrtime.bigint() % BigInt(1000000)); }
内容的提问来源于stack exchange,提问作者Faisal Amdani
相关产品推荐
相关产品推荐

