Skip to content

Commit

Permalink
Merge pull request #6 from lefinal/add-utc-time-valuer
Browse files Browse the repository at this point in the history
feat: add full utc time
  • Loading branch information
lefinal authored Jun 23, 2022
2 parents a516ab7 + be652d5 commit b2caabd
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 45 deletions.
23 changes: 6 additions & 17 deletions time.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,21 +61,10 @@ func (t Time) Value() (driver.Value, error) {
}.Value()
}

// timeUTCValuer wraps Time for satisfying driver.Value with UTC time.
type timeUTCValuer struct {
time Time
}

// Value returns the value for satisfying the driver.Valuer interface. The
// returned time will be in UTC if not null.
func (t timeUTCValuer) Value() (driver.Value, error) {
return sql.NullTime{
Time: t.time.Time.UTC(),
Valid: t.time.Valid,
}.Value()
}

// UTC returns a driver.Valuer that uses UTC time if not null.
func (t Time) UTC() driver.Valuer {
return timeUTCValuer{time: t}
// UTC returns the UTC time.
func (t Time) UTC() Time {
return Time{
Time: t.Time.UTC(),
Valid: t.Valid,
}
}
37 changes: 9 additions & 28 deletions time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,33 +114,14 @@ func TestTime_Value(t *testing.T) {
suite.Run(t, new(TimeValueSuite))
}

// TimeUTCSuite tests Time.UTC.
type TimeUTCSuite struct {
suite.Suite
}

func (suite *TimeUTCSuite) TestNull() {
tt := Time{Time: testTime}
raw, err := tt.UTC().Value()
suite.Require().NoError(err, "should not fail")
suite.Nil(raw, "should return correct value")
}

func (suite *TimeUTCSuite) TestOK() {
tt := NewTime(testTime)
loc, err := time.LoadLocation("America/New_York")
if err != nil {
panic(err)
}
tt.Time.In(loc)
raw, err := tt.UTC().Value()
suite.Require().NoError(err, "should not fail")
rawTime, ok := raw.(time.Time)
suite.Require().True(ok, "returned valued should be time")
suite.NotEqual(rawTime, testTime, "times should differ")
suite.Equal(rawTime, testTime.UTC(), "should return correct value")
}

func TestTime_UTC(t *testing.T) {
suite.Run(t, new(TimeUTCSuite))
tt := Time{
Time: time.UnixMilli(1958323),
Valid: true,
}
utc := tt.UTC()
assert.Equal(t, Time{
Time: tt.Time.UTC(),
Valid: tt.Valid,
}, utc, "should return correct value")
}

0 comments on commit b2caabd

Please sign in to comment.