From a1d104faec9c5689bc5efd76c2b1820882ab3c93 Mon Sep 17 00:00:00 2001 From: Peter Bourgon Date: Wed, 6 Sep 2023 21:25:06 +0200 Subject: [PATCH] Add ulid.Timestamp method (#107) --- ulid.go | 5 +++++ ulid_test.go | 22 +++++++++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/ulid.go b/ulid.go index 8f37026..2064dd4 100644 --- a/ulid.go +++ b/ulid.go @@ -411,6 +411,11 @@ func (id ULID) Time() uint64 { uint64(id[1])<<32 | uint64(id[0])<<40 } +// Timestamp returns the time encoded in the ULID as a time.Time. +func (id ULID) Timestamp() time.Time { + return Time(id.Time()) +} + // maxTime is the maximum Unix time in milliseconds that can be // represented in a ULID. var maxTime = ULID{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}.Time() diff --git a/ulid_test.go b/ulid_test.go index 47f3b30..43f81c6 100644 --- a/ulid_test.go +++ b/ulid_test.go @@ -393,7 +393,6 @@ func TestTime(t *testing.T) { t.Errorf("difference between original and recovered time (%d) greater"+ "than a millisecond", diff) } - } func TestTimestampRoundTrips(t *testing.T) { @@ -434,6 +433,27 @@ func TestULIDTime(t *testing.T) { } } +func TestULIDTimestamp(t *testing.T) { + t.Parallel() + + { + id := ulid.Make() + ts := id.Timestamp() + tt := ulid.Time(id.Time()) + if ts != tt { + t.Errorf("id.Timestamp() %s != ulid.Time(id.Time()) %s", ts, tt) + } + } + + { + now := time.Now() + id := ulid.MustNew(ulid.Timestamp(now), ulid.DefaultEntropy()) + if want, have := now.Truncate(time.Millisecond), id.Timestamp(); want != have { + t.Errorf("Timestamp: want %v, have %v", want, have) + } + } +} + func TestEntropy(t *testing.T) { t.Parallel()