weekly.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. weeklyParser struct{}
  12. weekly struct {
  13. times []*durationRange
  14. }
  15. )
  16. // 1,3,5/12:30-13:30|2,4,6/12:00-13:00
  17. func (p *weeklyParser) 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. ts := strings.Split(wt[1], "-")
  25. if len(ts) < 2 {
  26. return nil, fmt.Errorf("nonsupport params: %s", params)
  27. }
  28. startTime, err := parseDuration(ts[0])
  29. if err != nil {
  30. return nil, err
  31. }
  32. endTime, err := parseDuration(ts[1])
  33. if err != nil {
  34. return nil, err
  35. }
  36. for _, wd := range strings.Split(wt[0], ",") {
  37. w, ok := cherryString.ToInt64(wd)
  38. if !ok {
  39. return nil, fmt.Errorf("nonsupport params: %s", params)
  40. }
  41. newStartTime := time.Duration((w-1)*ctime.SecondsPerDay)*time.Second + startTime
  42. newEndTime := time.Duration((w-1)*ctime.SecondsPerDay)*time.Second + endTime
  43. times = append(times, &durationRange{
  44. startTime: newStartTime,
  45. endTime: newEndTime,
  46. })
  47. }
  48. }
  49. sort.Slice(times, func(i, j int) bool { return times[i].startTime < times[j].startTime })
  50. return &weekly{times: times}, nil
  51. }
  52. func (p *weekly) Between(t *ctime.CherryTime) bool {
  53. duration := t.Sub(t.StartOfWeek().Time).Seconds()
  54. for _, v := range p.times {
  55. if v.startTime.Seconds() <= duration && duration <= v.endTime.Seconds() {
  56. return true
  57. }
  58. }
  59. return false
  60. }
  61. func (p *weekly) TimeRange(t *ctime.CherryTime) (ctime.CherryTime, ctime.CherryTime) {
  62. weekStart := t.StartOfWeek()
  63. duration := t.Sub(weekStart.Time).Seconds()
  64. for _, v := range p.times {
  65. if duration <= v.startTime.Seconds() || duration <= v.endTime.Seconds() {
  66. startTime := ctime.NewTime(weekStart.Add(v.startTime), true)
  67. endTime := ctime.NewTime(weekStart.Add(v.endTime), true)
  68. return startTime, endTime
  69. }
  70. }
  71. // 下周
  72. nextTime := ctime.NewTime(weekStart.Add(7*24*time.Hour), true)
  73. return p.TimeRange(&nextTime)
  74. }