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

如何在JavaScript中将当前日期时间转换为UTC毫秒级时间戳?

解决JavaScript获取UTC时间戳的问题

嘿,其实你要找的方法早就藏在你已经写的代码里啦!

JavaScript中,new Date().getTime()返回的本身就是基于UTC 1970年1月1日00:00:00的毫秒数,和你的本地时区完全无关。换句话说,它就是你想要的“UTC时间的毫秒数”,不需要额外的getUTCTime()方法(这个方法确实不存在于Date对象里)。

举个简单的例子验证一下:

// 获取当前UTC时间戳(毫秒数)
const utcTimestamp = new Date().getTime();
// 或者更简洁的写法:
const utcTimestampShort = Date.now();

// 把时间戳转回UTC日期对象,验证它的UTC时间
const utcDate = new Date(utcTimestamp);
console.log(utcDate.toUTCString()); // 输出当前UTC时间的字符串格式
console.log(utcDate.getUTCFullYear()); // 输出UTC年份

如果你是想获取当天UTC时间的毫秒数(比如从UTC当天0点到现在的毫秒数),那可以通过UTC相关的时间方法手动计算:

const now = new Date();
const utcTimeOfDay = now.getUTCHours() * 3600000 + 
                     now.getUTCMinutes() * 60000 + 
                     now.getUTCSeconds() * 1000 + 
                     now.getUTCMilliseconds();

总结一下:

  • 要获取完整的UTC时间戳(从1970-01-01 UTC到现在的毫秒数):直接用new Date().getTime()或者Date.now()
  • 要获取UTC当天的时间偏移毫秒数:用上面的手动计算方法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:33:09