Created
October 19, 2010 17:09
-
-
Save hayesdavis/634586 to your computer and use it in GitHub Desktop.
Fun with snowflake
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
#First tweet on 21 Mar 2006 at 20:50:14.000 GMT (in ms) | |
TWEPOCH = 1288834974657 | |
#High 42 bytes are timestamp, low 22 are worker, datacenter and sequence bits | |
SHIFT = 22 | |
# Give it a snowflake id, it tells you what time it was created | |
# Will fail for very high ids because Ruby Time can only represent up to | |
# Jan 18, 2038 at 19:14:07 UTC (max signed int in seconds since unix epoch) | |
def what_time?(id) | |
Time.at(((id >> SHIFT)+TWEPOCH)/1000).utc | |
end | |
# Given a Ruby time object, it will give you the high part of a snowflake id | |
# Only goes up to 2038 thanks to Ruby Time limits | |
def id_at(time) | |
ms_since_twepoch = ((time.utc.to_i*1000)-TWEPOCH) | |
ms_since_twepoch << SHIFT | |
end | |
# Rough estimate (doesn't account for leap years, etc) of years from now that an id will occur | |
def years_from_now(id) | |
seconds = ((id >> SHIFT)+TWEPOCH)/1000 | |
seconds_from_now = seconds-Time.now.to_i | |
seconds_from_now/60.0/60/24/365 | |
end |
nevermind, i misread it.
@ryanking Not surprised. It's not the most readable code ever. Just something I hacked together after looking at your Scala IdWorker.
here's the mock we use: http://gist.github.com/637737
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Doesn't Time.at use seconds? (you need ms)