From 56a7ecbeb18dde53c6db4bd96b541fd9741b8d44 Mon Sep 17 00:00:00 2001 From: Cameron Moore Date: Sat, 24 Dec 2016 11:25:03 -0600 Subject: [PATCH] Add Unix epoch support to ToTimeE --- cast_test.go | 26 +++++++++++++++++++------- caste.go | 12 +++++++++--- 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/cast_test.go b/cast_test.go index 2e418ec..1312546 100644 --- a/cast_test.go +++ b/cast_test.go @@ -185,6 +185,25 @@ func TestIndirectPointers(t *testing.T) { assert.Equal(t, ToInt(z), 13) } +func TestToTimeE(t *testing.T) { + cases := []struct { + input interface{} + want time.Time + }{ + {"1979-05-27T07:32:00Z", time.Date(1979, 5, 27, 7, 32, 0, 0, time.UTC)}, + {"2016-03-06 15:28:01", time.Date(2016, 3, 6, 15, 28, 1, 0, time.UTC)}, + {1472574600, time.Date(2016, 8, 30, 16, 30, 0, 0, time.UTC)}, + {int(1482597504), time.Date(2016, 12, 24, 16, 38, 24, 0, time.UTC)}, + {int32(1234567890), time.Date(2009, 2, 13, 23, 31, 30, 0, time.UTC)}, + } + + for _, c := range cases { + v, err := ToTimeE(c.input) + assert.NoError(t, err) + assert.Equal(t, v.UTC(), c.want) + } +} + func TestToDuration(t *testing.T) { var td time.Duration = 5 tests := []struct { @@ -212,10 +231,3 @@ func TestToDuration(t *testing.T) { assert.Equal(t, v.expected, ToDuration(v.input)) } } - -func TestStringToDate(t *testing.T) { - d := "2016-03-06 15:28:01" - format := "2006-01-02 15:04:05" - v, _ := time.Parse(format, d) - assert.Equal(t, ToTime(d), v) -} diff --git a/caste.go b/caste.go index 23f0fe8..1aaa1ff 100644 --- a/caste.go +++ b/caste.go @@ -18,15 +18,21 @@ import ( func ToTimeE(i interface{}) (tim time.Time, err error) { i = indirect(i) - switch s := i.(type) { + switch v := i.(type) { case time.Time: - return s, nil + return v, nil case string: - d, e := StringToDate(s) + d, e := StringToDate(v) if e == nil { return d, nil } return time.Time{}, fmt.Errorf("Could not parse Date/Time format: %v\n", e) + case int: + return time.Unix(int64(v), 0), nil + case int32: + return time.Unix(int64(v), 0), nil + case int64: + return time.Unix(v, 0), nil default: return time.Time{}, fmt.Errorf("Unable to Cast %#v to Time\n", i) }