基于此
page
您可以使用这些静态方法将MongoDB ObjectID转换为时间戳,
java.util.Date
或者
java.time.Instant
对象:
public static Instant convertToInstantFrom(String objectId) {
return convertToDateFrom(objectId).toInstant();
}
public static Date convertToDateFrom(String objectId) {
return new Date(convertToTimestampFrom(objectId));
}
public static long convertToTimestampFrom(String objectId) {
return Long.parseLong(objectId.substring(0, 8), 16) * 1000;
}
如果运行以下代码段:
public static void main(String[] args) throws ParseException {
Stream.of("5b86bd41840a1be5a55c7022", "598af6efe4b09fc2332cf16a", "598ad932e4b0f0f169b42d5f")
.map(SimpleTests::convertToInstantFrom).forEach(System.out::println);
}
2018-08-29T15:35:29Z
2017-08-09T11:50:07Z
2017-08-09T09:43:14Z