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

在JavaScript中将时间值转换为微秒精度的Unix时间戳

如何将带微秒的ISO时间转换为微秒精度的Unix时间戳

JavaScript的Date对象仅支持毫秒精度,直接调用getTime()只能拿到毫秒级时间戳,微秒信息会丢失。要获取微秒精度的Unix时间戳,必须从原始的ISO时间字符串中提取微秒部分,再和毫秒级时间戳结合计算。

方法一:拆分字符串提取微秒

const isoStr = '2023-06-13T12:34:56.789123Z';
const timeValue = new Date(isoStr);

// 获取毫秒级时间戳(13位)
const msTimestamp = timeValue.getTime();
// 拆分字符串提取微秒部分(ISO格式中.后第4-6位)
const microSecPart = isoStr.split('.')[1]?.slice(3, 6) || '000';
// 计算微秒级时间戳(毫秒戳*1000 + 微秒数)
const microTimestamp = msTimestamp * 1000 + parseInt(microSecPart, 10);

console.log(microTimestamp); // 输出 1686659696789123

方法二:正则匹配提取各时间分量

const isoStr = '2023-06-13T12:34:56.789123Z';
const timeMatch = isoStr.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d{3})(\d{3})Z$/);

if (timeMatch) {
  // 用毫秒部分构造Date对象,获取毫秒时间戳
  const msDate = new Date(`${timeMatch[1]}-${timeMatch[2]}-${timeMatch[3]}T${timeMatch[4]}:${timeMatch[5]}:${timeMatch[6]}.${timeMatch[7]}Z`);
  const msTimestamp = msDate.getTime();
  // 提取微秒部分
  const microSec = parseInt(timeMatch[8], 10);
  // 组合成微秒级时间戳
  const microTimestamp = msTimestamp * 1000 + microSec;
  
  console.log(microTimestamp); // 输出 1686659696789123
}

注意事项

  • 若原始ISO字符串没有微秒部分(仅到毫秒),上述代码会默认微秒为000,保证结果格式统一。
  • 一旦将ISO字符串转为Date对象,微秒信息会被丢弃,因此务必保留原始字符串用于微秒提取。

内容的提问来源于stack exchange,提问作者Nghi Hoàng Đức

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 19:52:39