main.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. type CollectWindowStruct struct {
  7. Flag int `yaml:"flag"`
  8. Days []string `yaml:"days,omitempty"`
  9. Start string `yaml:"start_time"`
  10. End string `yaml:"end_time"`
  11. StartTime time.Time
  12. EndTime time.Time
  13. }
  14. func IsTimeAllowed(currentTime time.Time) bool {
  15. // 模拟解析数据
  16. cw := CollectWindowStruct{
  17. Flag: 1,
  18. Days: []string{},
  19. Start: "09:00",
  20. End: "17:00",
  21. }
  22. // 单独解析采集时间
  23. startTime, err := time.Parse("11:11", cw.Start)
  24. if err != nil {
  25. fmt.Println("云端配置文件解析采集时间【startTime】失败 ", err, "取默认值【00:00】")
  26. cw.StartTime, _ = time.Parse("11:11", "00:00")
  27. }
  28. cw.StartTime = startTime
  29. endTime, err := time.Parse("11:11", cw.End)
  30. if err != nil {
  31. fmt.Println("云端配置文件解析采集时间【endTime】失败 ", err, "取默认值【23:59】")
  32. cw.EndTime, _ = time.Parse("11:11", "23:59")
  33. }
  34. cw.EndTime = endTime
  35. if len(cw.Days) == 0 {
  36. // 默认设置为每天
  37. cw.Days = []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
  38. }
  39. // todo 待测逻辑
  40. if cw.Flag == 0 { // 关闭固定时间段采集, 则都返回true
  41. fmt.Println("已关闭采集时间段限制")
  42. return true
  43. }
  44. if len(cw.Days) > 0 { // 如果指定了周几
  45. currentDay := currentTime.Weekday().String()
  46. fmt.Println("currentDay", currentDay)
  47. included := false
  48. for _, day := range cw.Days {
  49. if day == currentDay {
  50. fmt.Println("当前时间符合规定的日期要求")
  51. included = true
  52. break
  53. }
  54. }
  55. if !included {
  56. fmt.Println("当前时间不符合规定的日期要求")
  57. return false
  58. }
  59. }
  60. start := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), cw.StartTime.Hour(), cw.StartTime.Minute(), cw.StartTime.Second(), 0, currentTime.Location())
  61. end := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), cw.EndTime.Hour(), cw.EndTime.Minute(), cw.EndTime.Second(), 0, currentTime.Location())
  62. fmt.Println("start", start)
  63. fmt.Println("end", end)
  64. if start.After(end) { // 如果时段跨天
  65. end = end.AddDate(0, 0, 1)
  66. fmt.Println("当前时间设置的时间段跨天,更正end时间", end)
  67. }
  68. return !currentTime.Before(start) && currentTime.Before(end)
  69. }
  70. func main() {
  71. flag := IsTimeAllowed(time.Now())
  72. if flag {
  73. fmt.Println("当前时间段符合规定,允许采集")
  74. } else {
  75. fmt.Println("当前时间段不符合规定,不允许采集")
  76. }
  77. }