Add Unix method to TimeDuration.

pull/85/head
Mariano Cano 5 years ago
parent b0240772da
commit 4c1a11c1bc

@ -113,11 +113,16 @@ func (t *TimeDuration) UnmarshalJSON(data []byte) error {
return errors.Errorf("failed to parse %s", data)
}
// Time calculates the embedded time.Time, sets it if necessary, and returns it.
// Time calculates the time if needed and returns it.
func (t *TimeDuration) Time() time.Time {
return t.RelativeTime(now())
}
// Unix calculates the time if needed it and returns the Unix time in seconds.
func (t *TimeDuration) Unix() int64 {
return t.RelativeTime(now()).Unix()
}
// RelativeTime returns the embedded time.Time or the base time plus the
// duration if this is not zero.
func (t *TimeDuration) RelativeTime(base time.Time) time.Time {

@ -217,6 +217,38 @@ func TestTimeDuration_Time(t *testing.T) {
}
}
func TestTimeDuration_Unix(t *testing.T) {
nowFn := now
defer func() {
now = nowFn
now()
}()
tm := time.Unix(1584198566, 535897000).UTC()
now = func() time.Time {
return tm
}
tests := []struct {
name string
timeDuration *TimeDuration
want int64
}{
{"zero", nil, -62135596800},
{"zero", &TimeDuration{}, -62135596800},
{"timestamp", &TimeDuration{t: tm}, 1584198566},
{"local", &TimeDuration{t: tm.Local()}, 1584198566},
{"duration", &TimeDuration{d: 1 * time.Hour}, 1584202166},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := tt.timeDuration.Unix()
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("TimeDuration.Unix() = %v, want %v", got, tt.want)
}
})
}
}
func TestTimeDuration_String(t *testing.T) {
nowFn := now
defer func() {

Loading…
Cancel
Save