如何将 Bson 时间戳从 Mongo changestream 转换为 Java 中的 UTC 日期格式?
How to Convert Bson Timestamp from Mongo changestream to UTC date format in Java?
例如:clusterTime = TimeStamp{value= 6948482818288648193, seconds = 16754329210, inc= 1}
当我从 document.getClusterTime().toString() 读取值时,返回的值是 bson 时间戳。我想将其转换为 UTC 时间格式。
BSON 时间戳值是一个 64 位数字,其中前 32 位表示自 00:00 UTC 的 1970-01-01 Unix 纪元以来的秒数。
下面是 mongoDB 文档的摘录:
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.
所以对于你的例子:
long timestampValue = 6_948_482_818_288_648_193L;
long unixTimestamp = timestampValue >> 32;
Instant timestamp = Instant.ofEpochSecond(unixTimestamp);
System.out.println(timestamp);
输出:
2021-04-07T18:22:07Z
打印结果为 UTC,由尾部 Z
表示。
例如:clusterTime = TimeStamp{value= 6948482818288648193, seconds = 16754329210, inc= 1}
当我从 document.getClusterTime().toString() 读取值时,返回的值是 bson 时间戳。我想将其转换为 UTC 时间格式。
BSON 时间戳值是一个 64 位数字,其中前 32 位表示自 00:00 UTC 的 1970-01-01 Unix 纪元以来的秒数。
下面是 mongoDB 文档的摘录:
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.
所以对于你的例子:
long timestampValue = 6_948_482_818_288_648_193L;
long unixTimestamp = timestampValue >> 32;
Instant timestamp = Instant.ofEpochSecond(unixTimestamp);
System.out.println(timestamp);
输出:
2021-04-07T18:22:07Z
打印结果为 UTC,由尾部 Z
表示。