Skip to content

Instantly share code, notes, and snippets.

@DarrenN
Created November 20, 2011 18:02
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save DarrenN/1380593 to your computer and use it in GitHub Desktop.
Save DarrenN/1380593 to your computer and use it in GitHub Desktop.
Short unique ID (Ruby)
t = DateTime
id = t.now.strftime("%Y%m%d%k%M%S%L") # Get current date to the milliseconds
id = id.to_i.to_s(36) # will generate somthing like "5i0sp1h4tkc"
# Reverse it
id.to_i(36)
@robmarable
Copy link

Thanks, this is nice!

If you're stuck on 1.8 which doesn't support %L in #strftime, here's a hack that takes advantage of the fact that #to_f returns the millis:

    now_f = Time.now.to_f
    now_i = now_f.to_s.delete('.').to_i
    now_i.to_s(36)

@christhesoul
Copy link

Yeah, thanks for this!

I had to change id = t.now.strftime("%Y%m%d%k%M%S%L") to use %H instead of %k as the blank padding in %k was causing issues if somebody did anything before 10am. :)

@Hungor
Copy link

Hungor commented Jul 3, 2018

Thanks for this

Based on this, I use the follow line, which I think is more precise due to the addition of sprintf.

id = sprintf("%20.10f", Time.now.to_f).delete('.').to_i.to_s(36)

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