diff --git a/cast.go b/cast.go index 8ef86f7..ffbb795 100644 --- a/cast.go +++ b/cast.go @@ -221,3 +221,36 @@ func AsDatetimeArray(values ...interface{}) ([]time.Time, bool) { } return arr, b } + +// AsDuration to convert as a duration +func AsDuration(v interface{}) (time.Duration, bool) { + switch d := v.(type) { + case time.Duration: + return d, true + case int, int8, int16, int32, int64: + return time.Duration(reflect.ValueOf(d).Int()), true + case float32, float64: + return time.Duration(int64(reflect.ValueOf(d).Float())), true + case string: + if du, err := time.ParseDuration(d); err == nil { + return du, true + } + return time.Duration(0), false + default: + return time.Duration(0), false + } +} + +// AsDurationArray to convert as an array of duration +func AsDurationArray(values ...interface{}) ([]time.Duration, bool) { + arr := make([]time.Duration, len(values)) + b := true + for i, v := range values { + if cv, ok := AsDuration(v); ok { + arr[i] = cv + continue + } + b = false + } + return arr, b +} diff --git a/cast_test.go b/cast_test.go index 30a7781..1c67c0f 100644 --- a/cast_test.go +++ b/cast_test.go @@ -157,6 +157,27 @@ func TestAsDatetimeArray(t *testing.T) { assert.Equal(t, []time.Time{timestamp, date, datetime, {}}, arr) } +func TestAsDuration(t *testing.T) { + duration := time.Second * 10 + + testDuration(t, duration, duration, true) + testDuration(t, 10000000000, duration, true) + testDuration(t, "10s", duration, true) + testDuration(t, "wrong", time.Duration(0), false) +} + +func TestAsDurationArray(t *testing.T) { + duration := time.Second * 10 + + arr, ok := cast.AsDurationArray(duration, 10000000000, "10s") + assert.True(t, ok) + assert.Equal(t, []time.Duration{duration, duration, duration}, arr) + + arr, ok = cast.AsDurationArray(duration, 10000000000, "10s", "wrong") + assert.False(t, ok) + assert.Equal(t, []time.Duration{duration, duration, duration, time.Duration(0)}, arr) +} + func testBool(t *testing.T, value interface{}, expected bool, ok bool) { b, o := cast.AsBool(value) assert.Equal(t, expected, b) @@ -186,3 +207,9 @@ func testDatetime(t *testing.T, value interface{}, expected time.Time, ok bool) assert.Equal(t, expected, b) assert.Equal(t, ok, o) } + +func testDuration(t *testing.T, value interface{}, expected time.Duration, ok bool) { + b, o := cast.AsDuration(value) + assert.Equal(t, expected, b) + assert.Equal(t, ok, o) +}