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

如何让JavaScript Date的toISOString()返回毫秒为000Z的UTC时间

实现方案

Date.prototype.toISOString()输出的毫秒位由Date对象本身存储的毫秒值决定,直接通过new Date()创建的实例会携带当前系统时间的真实毫秒数,因此不会默认返回000后缀。你看到的其他示例返回000Z,是因为那些示例中的Date对象初始化时毫秒值本身就为0,并非方法默认做了归零处理。

要实现需求可采用以下两种常用方案:

  • 方案1:修改Date实例毫秒值为0(原生API操作,无格式兼容风险,更推荐)
// 高可读性分步写法
const currentDate = new Date()
currentDate.setMilliseconds(0)
console.log(currentDate.toISOString()) 

// 链式简写写法
console.log(new Date(new Date().setMilliseconds(0)).toISOString())

输出示例:2021-10-14T08:28:28.000Z

  • 方案2:字符串截断拼接(适合临时快速处理场景)
const rawIso = new Date().toISOString()
const formattedIso = `${rawIso.split('.')[0]}.000Z`
console.log(formattedIso)

输出示例:2021-10-14T08:28:28.000Z


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 08:24:03