Created
June 8, 2018 03:19
-
-
Save panlw/4d0456bc98409284a405dd82128ef80a to your computer and use it in GitHub Desktop.
Timestamp in ObjectId of MongoDB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class EdpMongoUtil { | |
/** | |
* @param objectId ObjectId of MongoDB | |
* @return time of java.time.Instant | |
*/ | |
public static Instant timeFromObjectId(String objectId) { | |
return Instant.ofEpochMilli(Integer.parseInt(objectId.substring(0, 8), 16) * 1000); | |
} | |
/** | |
* @param time time of java.time.Instant | |
* @return ObjectId of MongoDB | |
*/ | |
public static String objectIdFromTime(Instant time) { | |
return Integer.toString((int) (time.toEpochMilli() / 1000L), 16) + "0000000000000000"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment