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.
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
.