Skip to content

Instantly share code, notes, and snippets.

@panlw
Created June 8, 2018 03:19
Show Gist options
  • Save panlw/4d0456bc98409284a405dd82128ef80a to your computer and use it in GitHub Desktop.
Save panlw/4d0456bc98409284a405dd82128ef80a to your computer and use it in GitHub Desktop.
Timestamp in ObjectId of MongoDB
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