Skip to content

Commit

Permalink
Add pointer conversion utilities to transform int64 to time.Time (#1433)
Browse files Browse the repository at this point in the history
Adds pointer conversion `SecondsTimeValue` and `MillisecondsTimeValue` utilities for int64 to time.Time.

Fix #1432
  • Loading branch information
TylerBrock authored and jasdel committed Aug 1, 2017
1 parent e56e5a2 commit 71a6866
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
18 changes: 18 additions & 0 deletions aws/convert_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,24 @@ func TimeValue(v *time.Time) time.Time {
return time.Time{}
}

// SecondsTimeValue converts an int64 pointer to a time.Time value
// representing seconds since Epoch or time.Time{} if the pointer is nil.
func SecondsTimeValue(v *int64) time.Time {
if v != nil {
return time.Unix((*v / 1000), 0)
}
return time.Time{}
}

// MillisecondsTimeValue converts an int64 pointer to a time.Time value
// representing milliseconds sinch Epoch or time.Time{} if the pointer is nil.
func MillisecondsTimeValue(v *int64) time.Time {
if v != nil {
return time.Unix(0, (*v * 1000000))
}
return time.Time{}
}

// TimeUnixMilli returns a Unix timestamp in milliseconds from "January 1, 1970 UTC".
// The result is undefined if the Unix time cannot be represented by an int64.
// Which includes calling TimeUnixMilli on a zero Time is undefined.
Expand Down
33 changes: 33 additions & 0 deletions aws/convert_types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -435,3 +435,36 @@ func TestTimeMap(t *testing.T) {
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}

type TimeValueTestCase struct {
in int64
outSecs time.Time
outMillis time.Time
}

var testCasesTimeValue = []TimeValueTestCase{
{
in: int64(1501558289000),
outSecs: time.Unix(1501558289, 0),
outMillis: time.Unix(1501558289, 0),
},
{
in: int64(1501558289001),
outSecs: time.Unix(1501558289, 0),
outMillis: time.Unix(1501558289, 1*1000000),
},
}

func TestSecondsTimeValue(t *testing.T) {
for idx, testCase := range testCasesTimeValue {
out := SecondsTimeValue(&testCase.in)
assert.Equal(t, testCase.outSecs, out, "Unexpected value for time value at %d", idx)
}
}

func TestMillisecondsTimeValue(t *testing.T) {
for idx, testCase := range testCasesTimeValue {
out := MillisecondsTimeValue(&testCase.in)
assert.Equal(t, testCase.outMillis, out, "Unexpected value for time value at %d", idx)
}
}

0 comments on commit 71a6866

Please sign in to comment.