Skip to content

Commit

Permalink
Increase domain for model.TimeAsEpochMicroseconds
Browse files Browse the repository at this point in the history
Use `time.Unix()` instead of `time.UnixNano()` when the input exceeds the domain of `time.UnixNano()`

Signed-off-by: Prithvi Raj <p.r@uber.com>
  • Loading branch information
vprithvi committed Mar 7, 2018
1 parent cce04e7 commit d26d691
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
7 changes: 6 additions & 1 deletion model/time.go
Expand Up @@ -26,7 +26,12 @@ func EpochMicrosecondsAsTime(ts uint64) time.Time {
// TimeAsEpochMicroseconds converts time.Time to microseconds since epoch,
// which is the format the StartTime field is stored in the Span.
func TimeAsEpochMicroseconds(t time.Time) uint64 {
return uint64(t.UnixNano() / 1000)
if t.Year() > 1678 && t.Year() < 2262 {
// UnixNano's result is undefined if the Unix time in nanoseconds cannot be
// represented by an int64(less than year 1678 or greater than year 2262)
return uint64(t.UnixNano() / 1000)
}
return uint64(t.Unix() * 1e6)
}

// MicrosecondsAsDuration converts duration in microseconds to time.Duration value.
Expand Down
30 changes: 30 additions & 0 deletions model/time_test.go
Expand Up @@ -15,6 +15,7 @@
package model_test

import (
"math"
"testing"
"time"

Expand All @@ -39,3 +40,32 @@ func TestTimeZoneUTC(t *testing.T) {
ts := model.EpochMicrosecondsAsTime(10000100)
assert.Equal(t, time.UTC, ts.Location())
}

func TestTimeAsEpochMicroseconds(t *testing.T) {
tests := []struct {
name string
input time.Time
expected uint64
}{
{
name: "2018",
input: time.Date(2018, 0, 0, 0, 0, 0, 0, time.UTC),
expected: 1512000000000000,
},
{
name: "0",
input: time.Unix(0, 0),
expected: 0,
},
{
name: "large time",
input: time.Date(math.MaxInt64, 0, 0, 0, 0, 0, 0, time.UTC),
expected: 18384542515693551616,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.expected, model.TimeAsEpochMicroseconds(tt.input))
})
}
}

0 comments on commit d26d691

Please sign in to comment.