Pull the date with mongo _id on the client side

I use my _idclient-side document as strings. I would like you to be able to pull the timestamp out of this value as you can on the server. Is it possible to recreate this functionality on the client side? (recast as objectid or create a standalone function to pull this data)

example _id: "4f94c2a11a6bbec3872cb315"

Thank!

+3
source share
1 answer

How about this broken down into steps ... unfortunately, this is only the second resolution time that is stored in ObjectID.

var id = "4f94c2a11a6bbec3872cb315"​;
// first 4 bytes are the timestamp portion (8 hex chars)
var timehex = id.sub​string(0,8);
console.log(timehex); // gives: 4f94c2a1

// convert to a number... base 16
var secondsSinceEpoch = parseInt(timehex, 16);
console.log(secondsSinceEpoch); // gives: 1335149217

// convert to milliseconds, and create a new date
var dt = new Date(secondsSinceEpoch*1000);
console.log(dt);​ // gives: Sun Apr 22 2012 22:46:57 GMT-0400 (EDT)

See jsfiddle if you want to check: http://jsfiddle.net/pZdyM/

: kludgy - ObjectID. ObjectID , .

+9

All Articles