From ee1372208150aaa0cd36075bd050b690e7462e62 Mon Sep 17 00:00:00 2001 From: arturwwl <> Date: Mon, 22 Nov 2021 16:39:18 +0100 Subject: [PATCH] convert - String2Time accept HH:mm:ss format --- convert/time.go | 14 ++++++++++++++ convert/time_test.go | 5 +++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/convert/time.go b/convert/time.go index e53a19cd..47b067ca 100644 --- a/convert/time.go +++ b/convert/time.go @@ -15,6 +15,7 @@ import ( ) // String2Time converts a string to time with original location +// be aware for time strings (HH:mm:ss) returns zero year (LMT) for converted location func String2Time(s string, originalLocation *time.Location, convertedLocation *time.Location) (*time.Time, error) { if len(s) == 19 { if s == utils.ZeroTime0 || s == utils.ZeroTime1 { @@ -32,6 +33,7 @@ func String2Time(s string, originalLocation *time.Location, convertedLocation *t return nil, err } dt = dt.In(convertedLocation) + dt.IsZero() return &dt, nil } else if len(s) == 25 && s[10] == 'T' && s[19] == '+' && s[22] == ':' { dt, err := time.Parse(time.RFC3339, s) @@ -48,6 +50,18 @@ func String2Time(s string, originalLocation *time.Location, convertedLocation *t } dt = dt.In(convertedLocation) return &dt, nil + } else if len(s) == 8 && s[2] == ':' && s[5] == ':' { + currentDate := time.Now() + dt, err := time.ParseInLocation("15:04:05", s, originalLocation) + if err != nil { + return nil, err + } + // add current date for correct time locations + dt = dt.AddDate(currentDate.Year(), int(currentDate.Month()), currentDate.Day()) + dt = dt.In(convertedLocation) + // back to zero year + dt = dt.AddDate(-currentDate.Year(), int(-currentDate.Month()), -currentDate.Day()) + return &dt, nil } else { i, err := strconv.ParseInt(s, 10, 64) if err == nil { diff --git a/convert/time_test.go b/convert/time_test.go index ef01b362..c1346fad 100644 --- a/convert/time_test.go +++ b/convert/time_test.go @@ -15,12 +15,13 @@ func TestString2Time(t *testing.T) { expectedLoc, err := time.LoadLocation("Asia/Shanghai") assert.NoError(t, err) - var kases = map[string]time.Time{ + var cases = map[string]time.Time{ "2021-06-06T22:58:20+08:00": time.Date(2021, 6, 6, 22, 58, 20, 0, expectedLoc), "2021-07-11 10:44:00": time.Date(2021, 7, 11, 18, 44, 0, 0, expectedLoc), "2021-08-10T10:33:04Z": time.Date(2021, 8, 10, 18, 33, 04, 0, expectedLoc), + "10:22:33": time.Date(0, 1, 1, 18, 22, 33, 0, expectedLoc), } - for layout, tm := range kases { + for layout, tm := range cases { t.Run(layout, func(t *testing.T) { target, err := String2Time(layout, time.UTC, expectedLoc) assert.NoError(t, err)