MongoDB中ObjectId.getTimestamp()返回时间与本地时间不符的原因咨询
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
ObjectIdstarts with 4 bytes that represent a Unix timestamp in UTC. - The
getTimestamp()method just extracts those 4 bytes and converts them into anISODateformat, which always displays the UTC time (that's what theZat the end of the date string stands for).
Looking at your example:
You created the
ObjectIdat your local time 20:12x.getTimestamp()returnedISODate("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

