diff --git a/core.go b/core.go index 3eba7f1..75bb1a8 100644 --- a/core.go +++ b/core.go @@ -2,11 +2,13 @@ package time_arrow import ( "fmt" - "github.com/google/uuid" "log" "sort" "strings" + "sync" "time" + + "github.com/google/uuid" ) type TimeArrowType string @@ -116,10 +118,27 @@ func isInDayOfMonth(t time.Time, ta TimeArrow) bool { return false } +var isInTimeOfDayCacheBool sync.Map + func isInTimeOfDay(t time.Time, ta TimeArrow) bool { + if len(ta.TimesOnDay) == 0 { return true } + + tfdate := t.Format("2006-01-02") + + mainKey := fmt.Sprintf("[%s][%s]", tfdate, strings.Join(ta.TimesOnDay, "|")) + value, ok := isInTimeOfDayCacheBool.Load(mainKey) + if ok { + ret, ok := value.(bool) + if ok { + return ret + } + } + + parseInLocationCache := map[string]time.Time{} + var err error for k := range ta.TimesOnDay { tsp := strings.Split(ta.TimesOnDay[k], "-") if len(tsp) < 2 { @@ -128,20 +147,44 @@ func isInTimeOfDay(t time.Time, ta TimeArrow) bool { } start, end := tsp[0], tsp[1] + start = timeCompletion(start) end = timeCompletion(end) - startTime, err := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s %s", t.Format("2006-01-02"), start), time.Local) - if err != nil { - log.Println("时间段开始时间格式错误", start) - continue + + startTimeKey := fmt.Sprintf("%s %s", tfdate, start) + startTime, ok := parseInLocationCache[startTimeKey] + if !ok { + startTime, err = time.ParseInLocation("2006-01-02 15:04:05", startTimeKey, time.Local) + parseInLocationCache[startTimeKey] = startTime + if err != nil { + log.Println("时间段开始时间格式错误", start) + continue + } + } else { + if startTime.IsZero() { + log.Println("时间段开始时间格式错误", start) + continue + } } + if end == "24" || end == "24:00" || end == "24:00:00" { end = "23:59:59" } - endTime, err := time.ParseInLocation("2006-01-02 15:04:05", fmt.Sprintf("%s %s", t.Format("2006-01-02"), end), time.Local) - if err != nil { - log.Println("时间段结束时间格式错误", end) - continue + + endTimeKey := fmt.Sprintf("%s %s", tfdate, end) + endTime, ok := parseInLocationCache[endTimeKey] + if !ok { + endTime, err = time.ParseInLocation("2006-01-02 15:04:05", endTimeKey, time.Local) + parseInLocationCache[endTimeKey] = endTime + if err != nil { + log.Println("时间段结束时间格式错误", end) + continue + } + } else { + if endTime.IsZero() { + log.Println("时间段结束时间格式错误", end) + continue + } } if startTime.Unix() > endTime.Unix() { @@ -150,9 +193,11 @@ func isInTimeOfDay(t time.Time, ta TimeArrow) bool { } if (t.After(startTime) || t.Equal(startTime)) && t.Before(endTime) { + isInTimeOfDayCacheBool.Store(mainKey, true) return true } } + isInTimeOfDayCacheBool.Store(mainKey, false) return false }