Skip to content

Instantly share code, notes, and snippets.

@esquinas
Last active December 24, 2020 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esquinas/707f4f7d1a70dd2c8231bcfa74879194 to your computer and use it in GitHub Desktop.
Save esquinas/707f4f7d1a70dd2c8231bcfa74879194 to your computer and use it in GitHub Desktop.
Convert a timestamp to MongoDB ObjectId to get fast (indexed) create_at queries for free.
# USAGE:
# ------
# mongo_id_from_date Date.parse('2020-12-24') # => "5fe3da000000000000000000"
# mongo_id_from_date(Time.now) # => "5fe471d90000000000000000"
def mongo_id_from_date(date)
min_date = Time.at 0
max_date = Time.at 0xffffffff
raise "Error: date must be between #{min_date.to_date} and #{max_date.to_date}" if date < min_date || date > max_date
hex_seconds = date.to_time.to_i.to_s(16)
"#{hex_seconds.rjust(8, '0')}0000000000000000"
end
# LINKS:
# -----
# - [MongoDB ObjectID to Timestamp converter (and vice-versa)](https://github.com/SteveRidout/mongo-object-time)
# - [MongoDB ObjectId ↔ Timestamp Converter](http://steveridout.github.io/mongo-object-time/)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment