The MongoDB ObjectID contains an embedded timestamp of its creation time. How can you extract this timestamp with plain Java without using classes of a driver library?
MongoDB creates object id's that typically look like:
5b86bd41840a1be5a55c7022
598af6efe4b09fc2332cf16a
598ad932e4b0f0f169b42d5f
The extraction target can be either a long, java.util.Date or a java.time.Instant.
Based on this page you could convert with these static methods the MongoDB ObjectID to a timestamp, java.util.Date or a java.time.Instant object:
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;
}
If you run the following code snippet:
public static void main(String[] args) throws ParseException {
Stream.of("5b86bd41840a1be5a55c7022", "598af6efe4b09fc2332cf16a", "598ad932e4b0f0f169b42d5f")
.map(SimpleTests::convertToInstantFrom).forEach(System.out::println);
}
You will see this result on the console:
2018-08-29T15:35:29Z
2017-08-09T11:50:07Z
2017-08-09T09:43:14Z
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With