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

如何自动将ISO 8601格式时间字符串转换为Timestamp?

无需手动处理字符,将ISO 8601时间字符串转为时间戳

你之前的代码核心问题在于用空格分割字符串,但目标ISO 8601格式字符串是用T分隔日期和时间,因此split(" ")无法正确拆分内容,导致后续解构操作失败。

实际上JavaScript的Date构造函数原生支持解析ISO 8601格式的时间字符串,完全不需要手动移除T和Z,直接传入即可生成对应的Date对象,再调用getTime()就能获取毫秒级时间戳。

最简解决方案

const str = "2022-12-24T16:00:00Z";
// 直接用Date构造函数解析ISO格式字符串
const date = new Date(str);
// 获取毫秒级时间戳
const timestamp = date.getTime();
console.log(timestamp); // 输出:1671897600000

补充:获取秒级时间戳

如果需要秒级时间戳,只需对结果做简单转换:

const timestampInSeconds = Math.floor(date.getTime() / 1000);
console.log(timestampInSeconds); // 输出:1671897600

手动拆分的备选方案(不推荐)

如果一定要手动处理字符串(不建议,原生解析更可靠且不易出错),可以用T分割日期和时间部分,再移除Z,同时注意用Date.UTC确保解析的是UTC时间:

const str = "2022-12-24T16:00:00Z";
const [datePart, timePart] = str.split("T");
const cleanTimePart = timePart.replace("Z", "");

const [year, month, day] = datePart.split("-");
const [hours, minutes, seconds] = cleanTimePart.split(":");

// 使用UTC方法构造日期,避免时区偏差
const date = new Date(Date.UTC(+year, month - 1, +day, +hours, +minutes, +seconds));
const timestamp = date.getTime();
console.log(timestamp); // 输出:1671897600000

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 00:30:44