Skip to content

Commit 94d24b6

Browse files
committed
crtime: add Mono.ToUTC
Add a method to produce a UTC time using the current clock.
1 parent 1264a2e commit 94d24b6

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

crtime/monotonic.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,18 @@ func (m Mono) Elapsed() time.Duration {
4444
return time.Duration(NowMono() - m)
4545
}
4646

47+
// ToUTC returns the UTC time corresponding to the monotonic time.
48+
//
49+
// The time is derived from the current wall clock, adjusted by the difference
50+
// in the monotonic clock values. Note that if the wall clock has been changed
51+
// since the Mono value was obtained, the result does not reflect the wall clock
52+
// at that point in time.
53+
func (m Mono) ToUTC() time.Time {
54+
now := time.Now()
55+
adjustment := time.Duration(m) - now.Sub(startTime)
56+
return now.UTC().Add(adjustment)
57+
}
58+
4759
// MonoFromTime converts a time.Time to a Mono value. If the time has a
4860
// monotonic component, it is used.
4961
func MonoFromTime(t time.Time) Mono {

crtime/monotonic_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,17 @@ func TestMono(t *testing.T) {
3030
d := NowMono()
3131
require.LE(t, b, c)
3232
require.LE(t, c, d)
33+
34+
t.Run("ToUTC", func(t *testing.T) {
35+
const d = 50 * time.Millisecond
36+
const tolerance = time.Millisecond
37+
38+
start := NowMono()
39+
expected := time.Now().UnixNano()
40+
time.Sleep(d)
41+
actual := start.ToUTC().UnixNano()
42+
if actual < expected-tolerance.Nanoseconds() || actual > expected+tolerance.Nanoseconds() {
43+
t.Fatalf("actual - expected = %s", time.Duration(actual-expected))
44+
}
45+
})
3346
}

0 commit comments

Comments
 (0)