Skip to content

Add ObjectId to conversion types #48

Description

@MrSinaRJ

Hi,
Thanks for the great tool you've developed. I use it daily and find it very easy to use.

Please add the ability to convert ObjectId (MongoDB time-based id) to timestamp and vice-versa. here is a code snippet suggestion for the convert:

// Convert ObjectId string to Date
function objectIdToDate(objectId) {
  const timestampHex = objectId.substring(0, 8); // first 4 bytes
  const timestamp = parseInt(timestampHex, 16);  // convert hex to int
  return new Date(timestamp * 1000);             // seconds to ms
}

// Convert Date to ObjectId string
function dateToObjectId(date) {
  const seconds = Math.floor(date.getTime() / 1000);
  const hexSeconds = seconds.toString(16).padStart(8, "0");
  return hexSeconds + "0000000000000000"; // pad to 24 hex chars
}

// Example usage:

console.log(objectIdToDate("6523a4c8c2b9b4a0f6e4a111")); 
// output: 2023-10-09T06:59:20.000Z

console.log(dateToObjectId(new Date(2025, 9, 12))); 
// output: 68eabe480000000000000000

It's not that easy, but it can make your tool more universal by adding this simple code.

Here is the breakdown of what the bytes in ObjectId means:

4 bytes: Unix timestamp (creation time, second precision)
5 bytes: random value (machine + process)
3 bytes: incrementing counter

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions