You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Node.js中实现Windows时间转Unix时间戳?现有代码异常

Windows时间转日期:Node.js代码错误分析与修复

问题场景

用户已通过Python实现Windows时间转日期的功能,代码如下:

def convert_windows_time(windows_time):
    return datetime.datetime(1601, 1, 1) + datetime.timedelta(microseconds=windows_time / 10)

但在Node.js中尝试相同逻辑时得到错误日期,原Node.js代码:

let a = parseInt(129436810067618693)
let b = (new Date('1601-01-01').getMilliseconds()) + a / 10
console.log(new Date(b / 10000))

错误原因分析

  • 整数精度丢失:129436810067618693超出了JavaScript安全整数范围(2^53-1,即9007199254740991),用parseInt转换会直接丢失精度,导致后续计算全部错误。
  • 基准时间处理错误:new Date('1601-01-01').getMilliseconds()获取的是该日期的毫秒部分(固定为0),而非1601-01-01对应的Unix时间戳(毫秒数),完全搞错了基准值的获取方式。
  • 单位换算逻辑混乱:Windows时间的单位是100纳秒(1单位=0.1微秒),转换为毫秒需除以10000,原代码的分步换算逻辑完全错误,导致时间偏移量计算偏差。

正确的Node.js实现

function convertWindowsTime(windowsTime) {
    // 获取Windows时间基准点(1601-01-01)的Unix时间戳(毫秒)
    const windowsEpoch = new Date('1601-01-01').getTime();
    // Windows时间单位是100纳秒,转换为毫秒需除以10000,用BigInt避免精度丢失
    const offsetMs = BigInt(windowsTime) / 10000n;
    // 基准时间戳加上偏移量,得到最终日期
    return new Date(windowsEpoch + Number(offsetMs));
}

// 测试示例
const windowsTime = 129436810067618693n;
console.log(convertWindowsTime(windowsTime));

内容的提问来源于stack exchange,提问作者daisy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 23:42:13