Skip to content

Commit

Permalink
Add ulid.Timestamp method
Browse files Browse the repository at this point in the history
  • Loading branch information
peterbourgon committed Aug 25, 2023
1 parent b4f9914 commit 0ecc433
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
5 changes: 5 additions & 0 deletions ulid.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
22 changes: 21 additions & 1 deletion ulid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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()

Expand Down

0 comments on commit 0ecc433

Please sign in to comment.