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

MongoDB中ObjectId.getTimestamp()返回时间与本地时间不符的原因咨询

Why does ObjectId.getTimestamp() return a time different from my local creation time?

Hey there! That time difference you're seeing is totally normal—it's all about time zones, and neither your ObjectId nor the getTimestamp() function is broken.

Let me break it down simply: MongoDB's ObjectId uses UTC time for its embedded timestamp, not your local machine's time zone. Here's the lowdown:

  • Every ObjectId starts with 4 bytes that represent a Unix timestamp in UTC.
  • The getTimestamp() method just extracts those 4 bytes and converts them into an ISODate format, which always displays the UTC time (that's what the Z at the end of the date string stands for).

Looking at your example:

You created the ObjectId at your local time 20:12
x.getTimestamp() returned ISODate("2018-04-04T14:41:58Z")

If you convert that UTC time to your local time zone, you'll find it lines up almost perfectly with when you created the ObjectId. For instance, if your local time zone is UTC+5:30, adding 5 hours and 30 minutes to 14:41:58 UTC gives you ~20:11:58—just a few seconds off from your stated 20:12, which makes sense because of the small delay between running new ObjectId() and x.getTimestamp().

One more quick note: MongoDB defaults to UTC for all time-related storage, which is a standard best practice to avoid confusion across different time zones in distributed systems.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:42:32