| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- package openTime
- import (
- "fmt"
- "sort"
- "strings"
- "time"
- cherryString "github.com/cherry-game/cherry/extend/string"
- ctime "github.com/cherry-game/cherry/extend/time"
- )
- type (
- weeklyContinualParser struct{}
- weeklyContinual struct {
- times []*durationRange
- }
- )
- // 1/8:00-3/24:00|1/8:00-3/24:00
- func (p *weeklyContinualParser) Parse(params string) (OpenTime, error) {
- times := []*durationRange{}
- for _, v := range strings.Split(params, "|") {
- wt := strings.Split(v, "-")
- if len(wt) < 2 {
- return nil, fmt.Errorf("nonsupport params: %s", params)
- }
- startTime, err := p.toWeekTime(wt[0])
- if err != nil {
- return nil, err
- }
- endTime, err := p.toWeekTime(wt[1])
- if err != nil {
- return nil, err
- }
- times = append(times, &durationRange{
- startTime: startTime,
- endTime: endTime,
- })
- }
- sort.Slice(times, func(i, j int) bool { return times[i].startTime < times[j].startTime })
- return &weeklyContinual{times: times}, nil
- }
- func (p *weeklyContinualParser) toWeekTime(str string) (time.Duration, error) {
- s := strings.Split(str, "/")
- if len(s) < 2 {
- return 0, fmt.Errorf("nonsupport params: %s", str)
- }
- w, ok := cherryString.ToInt64(s[0])
- if !ok {
- return 0, fmt.Errorf("nonsupport params: %s", str)
- }
- t, err := parseDuration(s[1])
- if err != nil {
- return 0, err
- }
- duration := time.Duration((w-1)*ctime.SecondsPerDay)*time.Second + t
- return duration, nil
- }
- func (p *weeklyContinual) Between(t *ctime.CherryTime) bool {
- duration := t.Sub(t.StartOfWeek().Time).Seconds()
- for _, v := range p.times {
- if v.startTime.Seconds() <= duration && duration <= v.endTime.Seconds() {
- return true
- }
- }
- return false
- }
- func (p *weeklyContinual) TimeRange(t *ctime.CherryTime) (ctime.CherryTime, ctime.CherryTime) {
- weekStart := t.StartOfWeek()
- duration := t.Sub(weekStart.Time).Seconds()
- for _, v := range p.times {
- if duration <= v.startTime.Seconds() || duration <= v.endTime.Seconds() {
- startTime := ctime.NewTime(weekStart.Add(v.startTime), true)
- endTime := ctime.NewTime(weekStart.Add(v.endTime), true)
- return startTime, endTime
- }
- }
- // 下周
- nextTime := ctime.NewTime(weekStart.Add(7*24*time.Hour), true)
- return p.TimeRange(&nextTime)
- }
|