weekly_continual.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package openTime
  2. import (
  3. "fmt"
  4. "sort"
  5. "strings"
  6. "time"
  7. cherryString "github.com/cherry-game/cherry/extend/string"
  8. ctime "github.com/cherry-game/cherry/extend/time"
  9. )
  10. type (
  11. weeklyContinualParser struct{}
  12. weeklyContinual struct {
  13. times []*durationRange
  14. }
  15. )
  16. // 1/8:00-3/24:00|1/8:00-3/24:00
  17. func (p *weeklyContinualParser) Parse(params string) (OpenTime, error) {
  18. times := []*durationRange{}
  19. for _, v := range strings.Split(params, "|") {
  20. wt := strings.Split(v, "-")
  21. if len(wt) < 2 {
  22. return nil, fmt.Errorf("nonsupport params: %s", params)
  23. }
  24. startTime, err := p.toWeekTime(wt[0])
  25. if err != nil {
  26. return nil, err
  27. }
  28. endTime, err := p.toWeekTime(wt[1])
  29. if err != nil {
  30. return nil, err
  31. }
  32. times = append(times, &durationRange{
  33. startTime: startTime,
  34. endTime: endTime,
  35. })
  36. }
  37. sort.Slice(times, func(i, j int) bool { return times[i].startTime < times[j].startTime })
  38. return &weeklyContinual{times: times}, nil
  39. }
  40. func (p *weeklyContinualParser) toWeekTime(str string) (time.Duration, error) {
  41. s := strings.Split(str, "/")
  42. if len(s) < 2 {
  43. return 0, fmt.Errorf("nonsupport params: %s", str)
  44. }
  45. w, ok := cherryString.ToInt64(s[0])
  46. if !ok {
  47. return 0, fmt.Errorf("nonsupport params: %s", str)
  48. }
  49. t, err := parseDuration(s[1])
  50. if err != nil {
  51. return 0, err
  52. }
  53. duration := time.Duration((w-1)*ctime.SecondsPerDay)*time.Second + t
  54. return duration, nil
  55. }
  56. func (p *weeklyContinual) Between(t *ctime.CherryTime) bool {
  57. duration := t.Sub(t.StartOfWeek().Time).Seconds()
  58. for _, v := range p.times {
  59. if v.startTime.Seconds() <= duration && duration <= v.endTime.Seconds() {
  60. return true
  61. }
  62. }
  63. return false
  64. }
  65. func (p *weeklyContinual) TimeRange(t *ctime.CherryTime) (ctime.CherryTime, ctime.CherryTime) {
  66. weekStart := t.StartOfWeek()
  67. duration := t.Sub(weekStart.Time).Seconds()
  68. for _, v := range p.times {
  69. if duration <= v.startTime.Seconds() || duration <= v.endTime.Seconds() {
  70. startTime := ctime.NewTime(weekStart.Add(v.startTime), true)
  71. endTime := ctime.NewTime(weekStart.Add(v.endTime), true)
  72. return startTime, endTime
  73. }
  74. }
  75. // 下周
  76. nextTime := ctime.NewTime(weekStart.Add(7*24*time.Hour), true)
  77. return p.TimeRange(&nextTime)
  78. }