Skip to content

Instantly share code, notes, and snippets.

@hayesdavis
Created October 19, 2010 17:09
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hayesdavis/634586 to your computer and use it in GitHub Desktop.
Save hayesdavis/634586 to your computer and use it in GitHub Desktop.
Fun with snowflake
#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
@ryanking
Copy link

Doesn't Time.at use seconds? (you need ms)

@ryanking
Copy link

nevermind, i misread it.

@hayesdavis
Copy link
Author

@ryanking Not surprised. It's not the most readable code ever. Just something I hacked together after looking at your Scala IdWorker.

@ryanking
Copy link

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