Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pull date from mongo _id on the client side

I use my document _id client-side as strings. I would love to be able pull the timestamp from 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"

Thanks!

like image 906
fancy Avatar asked Jan 17 '23 20:01

fancy


1 Answers

How about this, broken down into steps... unfortunately it's only second resolution time that gets stored in the 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 test: http://jsfiddle.net/pZdyM/

NOTE: this is kind of kludgy--it depends on the current ObjectID format. They might move the timestamp around within the ObjectID one day, and that would break this.

like image 69
Eve Freeman Avatar answered Jan 25 '23 17:01

Eve Freeman