Jon Kern
Jon Kern

Reputation: 3235

Convert MongoDB ObjectID to timestamp in Rails

How can I convert MongoDB IDs to their respective date? (I am not interested in using the Javascript technique with getTimestamp()...)

Upvotes: 1

Views: 853

Answers (1)

Jon Kern
Jon Kern

Reputation: 3235

In case you did not use timestamps! in MongoMapper or Mongoid, you can still get the created_at date from the ObjectID itself:

user = User.last
user.id
# => BSON::ObjectId('5a90731ddcd2d5008c000443')
user.id.generation_time.strftime('%Y-%m-%d %H:%M')
# => "2018-02-23 20:01"

For my future self...

Upvotes: 4

Related Questions