Cjoerg
Cjoerg

Reputation: 1325

How to convert a Mongoid _id into a timestamp (Rails)

I just read this SO post:

How are MongoDB's ObjectIds generated?

According to an answer there MongoDB ID's are not random and can be easily predicted. You can even convert it into a timestamp:

http://www.mongodb.org/display/DOCS/Object+IDs

I was wondering, is it possible to convert an _id (e.g. 52a435840000640002695268 or 52908452636872eda1000000) into a timestamp using the mongoidgem?

Upvotes: 3

Views: 2238

Answers (1)

sevenseacat
sevenseacat

Reputation: 25029

MongoDB IDs are parsed via Mongoid into instances of the class BSON::ObjectId, and that class has a method generation_time - http://rubydoc.info/gems/bson/2.0.0/BSON/ObjectId:generation_time

This gives you the time that the ID was generated at as a Ruby Time object, which I believe is what you were after.

Upvotes: 7

Related Questions