Reputation: 13
eg: clusterTime = TimeStamp{value= 6948482818288648193, seconds = 16754329210, inc= 1}
When I read the value from document.getClusterTime().toString() the value returned is bson timestamp. And I want to convert this into UTC time format.
Upvotes: 1
Views: 3196
Reputation: 5855
I couldn't find any documentation about that, but I solved that this way:
Convert BsonTimestamp
to java Date
: You need to multiply x 1000 to get milliseconds, and then use it in Date constructor
new java.util.Date((long)document.getTimestamp("clusterTime").getTime() * 1000)
The same with BsonDateTime
new java.util.Date((long)document.getTimestamp("clusterTime").getTime() * 1000)
Sourcecode (mongo-java-driver)
Upvotes: 0
Reputation: 86286
The BSON timestamp value is a 64 bits number where the first 32 bits denote a count of seconds since the Unix epoch of 1970-01-01 at 00:00 UTC.
Given below is an excerpt from the mongoDB documentation:
Timestamps
BSON has a special timestamp type for internal MongoDB use and is not associated with the regular Date type. This internal timestamp type is a 64 bit value where:
- the most significant 32 bits are a
time_t
value (seconds since the Unix epoch)- the least significant 32 bits are an incrementing
ordinal
for operations within a given second.
So for your example:
long timestampValue = 6_948_482_818_288_648_193L;
long unixTimestamp = timestampValue >> 32;
Instant timestamp = Instant.ofEpochSecond(unixTimestamp);
System.out.println(timestamp);
Output:
2021-04-07T18:22:07Z
The printed result is in UTC, denoted by the trailing Z
.
Link: BSON Types - MongoDB Manual
Upvotes: 3