diff --git a/os/gtime/gtime.go b/os/gtime/gtime.go index 12f0346751e..b5e0e6d04e1 100644 --- a/os/gtime/gtime.go +++ b/os/gtime/gtime.go @@ -222,14 +222,13 @@ func StrToTime(str string, format ...string) (*Time, error) { } else if match = timeRegex2.FindStringSubmatch(str); len(match) > 0 && match[1] != "" { year, month, day = parseDateStr(match[1]) } else if match = timeRegex3.FindStringSubmatch(str); len(match) > 0 && match[1] != "" { - s := strings.ReplaceAll(match[2], ":", "") - if len(s) < 6 { - s += strings.Repeat("0", 6-len(s)) - } hour, _ = strconv.Atoi(match[1]) min, _ = strconv.Atoi(match[2]) sec, _ = strconv.Atoi(match[3]) nsec, _ = strconv.Atoi(match[4]) + if hour > 23 || min > 59 || sec > 59 { + return nil, gerror.NewCodef(gcode.CodeInvalidParameter, `invalid time string "%s"`, str) + } for i := 0; i < 9-len(match[4]); i++ { nsec *= 10 } @@ -240,13 +239,19 @@ func StrToTime(str string, format ...string) (*Time, error) { // Time if len(match[2]) > 0 { - s := strings.ReplaceAll(match[2], ":", "") - if len(s) < 6 { - s += strings.Repeat("0", 6-len(s)) + parts := strings.Split(match[2], ":") + if len(parts) >= 1 && parts[0] != "" { + hour, _ = strconv.Atoi(parts[0]) + } + if len(parts) >= 2 && parts[1] != "" { + min, _ = strconv.Atoi(parts[1]) + } + if len(parts) >= 3 && parts[2] != "" { + sec, _ = strconv.Atoi(parts[2]) + } + if hour > 23 || min > 59 || sec > 59 { + return nil, gerror.NewCodef(gcode.CodeInvalidParameter, `invalid time string "%s"`, str) } - hour, _ = strconv.Atoi(s[0:2]) - min, _ = strconv.Atoi(s[2:4]) - sec, _ = strconv.Atoi(s[4:6]) } // Nanoseconds, check and perform bits filling if len(match[3]) > 0 { diff --git a/os/gtime/gtime_z_unit_test.go b/os/gtime/gtime_z_unit_test.go index eae6eac074e..f644e429af6 100644 --- a/os/gtime/gtime_z_unit_test.go +++ b/os/gtime/gtime_z_unit_test.go @@ -183,6 +183,46 @@ func Test_StrToTime(t *testing.T) { } } + // test special time string + var testSpecialDateTimes = []string{ + "2006-01-02 8:04:05", + "2006-01-02 8:4:05", + "2006-01-02 8:4:5", + "2006-01-02 8:04:05.000", + "2006/01/02 8:4:5", + "2006.01.02 8:4:5.000", + "2006.01.02 - 8:4:5", + "2006.01.02 8:4:5 +0800 CST", + "2006-01-02T5:5:5+05:01", + "2006-01-01T19:3:5-05:01", + "2006-01-02T8:4:5", + "02-jan-2006 8:4:5", + "02/jan/2006 8:4:5", + "02.jan.2006 8:4:5", + "02.jan.2006:8:4:5", + } + for _, item := range testSpecialDateTimes { + timeTemp, err := gtime.StrToTime(item) + t.AssertNil(err) + t.Assert(timeTemp.Time.Local().Format("2006-01-02 15:04:05"), "2006-01-02 08:04:05") + } + + // test error time string + var testErrorDateTimes = []string{ + "2006-01-02 28:4:5", + "2006-01-02 8:60:5", + "2006-01-02 8:4:60", + "28:20:20", + "8:60:20", + "8:20:60", + } + for _, item := range testErrorDateTimes { + _, err := gtime.StrToTime(item) + if err == nil { + t.Error("test fail") + } + } + // test err _, err := gtime.StrToTime("2006-01-02 15:04:05", "aabbccdd") if err == nil {