问题描述
例如:clusterTime = TimeStamp{value= 6948482818288648193,seconds = 16754329210,inc= 1}
当我从 document.getClusterTime().toString() 读取值时,返回的值是 bson 时间戳。我想将其转换为 UTC 时间格式。
解决方法
BSON 时间戳值是一个 64 位数字,其中前 32 位表示自 Unix 纪元 1970-01-01 UTC 00:00 以来的秒数。
以下是 mongoDB 文档的摘录:
时间戳
BSON 有一个特殊的时间戳类型供 内部 MongoDB 使用 并且与常规日期类型无关。这个内部 时间戳类型是 64 位值,其中:
- 最高有效的 32 位是
time_t
值(自 Unix 时代) - 最低有效的 32 位是递增的
ordinal
用于给定秒内的操作。
例如:
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
表示。