From 0b0eb695e8ba99691ee61ae079d9a19da635217e Mon Sep 17 00:00:00 2001 From: donutloop Date: Thu, 30 Dec 2021 03:29:10 +0100 Subject: [PATCH] datetime: optimized func calls (#7) Replace time parsing calls with less expensive operations --- datetime/datetime.go | 25 +++++++++++-------------- datetime/datetime_test.go | 5 ++++- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/datetime/datetime.go b/datetime/datetime.go index f37e3fb..547f6a3 100644 --- a/datetime/datetime.go +++ b/datetime/datetime.go @@ -25,7 +25,7 @@ package datetime import ( - "strconv" + "fmt" "time" ) @@ -56,24 +56,17 @@ func init() { // AddMinute add or sub minute to the time func AddMinute(t time.Time, minute int64) time.Time { - s := strconv.FormatInt(minute, 10) - m, _ := time.ParseDuration(s + "m") - return t.Add(m) + return t.Add(time.Minute * time.Duration(minute)) } // AddHour add or sub hour to the time func AddHour(t time.Time, hour int64) time.Time { - s := strconv.FormatInt(hour, 10) - h, _ := time.ParseDuration(s + "h") - return t.Add(h) + return t.Add(time.Hour * time.Duration(hour)) } // AddDay add or sub day to the time func AddDay(t time.Time, day int64) time.Time { - dayHours := day * 24 - d := strconv.FormatInt(dayHours, 10) - h, _ := time.ParseDuration(d + "h") - return t.Add(h) + return t.Add(24 * time.Hour * time.Duration(day)) } // GetNowDate return format yyyy-mm-dd of current date @@ -109,7 +102,11 @@ func FormatTimeToStr(t time.Time, format string) string { } // FormatStrToTime convert string to time -func FormatStrToTime(str, format string) time.Time { - t, _ := time.Parse(timeFormat[format], str) - return t +func FormatStrToTime(str, format string) (time.Time, error) { + v, ok := timeFormat[format] + if !ok { + return time.Time{}, fmt.Errorf("format %s not found", format) + } + + return time.Parse(v, str) } diff --git a/datetime/datetime_test.go b/datetime/datetime_test.go index 4a6e0cc..4348192 100644 --- a/datetime/datetime_test.go +++ b/datetime/datetime_test.go @@ -135,7 +135,10 @@ func TestFormatStrToTime(t *testing.T) { "2021/01"} for i := 0; i < len(cases); i++ { - res := FormatStrToTime(datetimeStr[i], cases[i]) + res, err := FormatStrToTime(datetimeStr[i], cases[i]) + if err != nil { + t.Fatal(err) + } expected, _ := time.Parse(formats[i], datetimeStr[i]) if res != expected { utils.LogFailedTestInfo(t, "FormatTimeToStr", cases[i], expected, res)