4

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!

4

1 回答 1

9

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.

于 2012-04-27T07:14:08.023 回答