Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert the MongoDB object id to a Java Date or Instant using Java

Tags:

java

mongodb

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.

like image 478
gil.fernandes Avatar asked May 02 '26 12:05

gil.fernandes


1 Answers

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
like image 164
gil.fernandes Avatar answered May 05 '26 01:05

gil.fernandes