Last active
December 24, 2020 10:59
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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