Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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) >> SHIFT)+TWEPOCH)/1000).utc
# 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
# 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 =
Copy link

ryanking commented Oct 20, 2010

Doesn't use seconds? (you need ms)

Copy link

ryanking commented Oct 20, 2010

nevermind, i misread it.

Copy link

hayesdavis commented Oct 20, 2010

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

Copy link

ryanking commented Oct 21, 2010

here's the mock we use:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment