diff --git a/README.md b/README.md index af29146..8284e93 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ ULID.generate You can also input a seed time which will consistently give you the same string for the time component. This is useful for migrating to ulid. ```crystal -ULID.generate Time.now + 5.second +ULID.generate Time.utc + 5.second # => "01ARYZ6S41TSV4RRFFQ69G5FAV" ``` diff --git a/spec/ulid_spec.cr b/spec/ulid_spec.cr index 994fa71..9c58e01 100644 --- a/spec/ulid_spec.cr +++ b/spec/ulid_spec.cr @@ -51,7 +51,7 @@ describe ULID do 1000.times do ulid_1 = ULID.generate sleep 1.millisecond - ulid_2 = ULID.generate(Time.now - 1.second) + ulid_2 = ULID.generate(Time.utc - 1.second) (ulid_2 < ulid_1).should be_true end diff --git a/src/ulid.cr b/src/ulid.cr index bead01c..2bf7658 100644 --- a/src/ulid.cr +++ b/src/ulid.cr @@ -15,18 +15,18 @@ module ULID # ULID.generate # # => "01B3EAF48P97R8MP9WS6MHDTZ3" # ``` - def generate(seed_time : Time = Time.now) : String + def generate(seed_time : Time = Time.utc) : String encode_time(seed_time, TIME_LEN) + encode_random(RANDOM_LEN) end private def encode_time(now : Time, len : Int32) : String - ms = now.epoch_ms + ms = now.to_unix_ms String.build do |io| len.times do |i| mod = ms % ENCODING_LEN io << ENCODING[mod] - ms = (ms - mod) / ENCODING_LEN + ms = (ms - mod) // ENCODING_LEN end end.reverse end