12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- package main
- import (
- "fmt"
- "time"
- )
- type CollectWindowStruct struct {
- Flag int `yaml:"flag"`
- Days []string `yaml:"days,omitempty"`
- Start string `yaml:"start_time"`
- End string `yaml:"end_time"`
- StartTime time.Time
- EndTime time.Time
- }
- func IsTimeAllowed(currentTime time.Time) bool {
- // 模拟解析数据
- cw := CollectWindowStruct{
- Flag: 1,
- Days: []string{},
- Start: "09:00",
- End: "17:00",
- }
- // 单独解析采集时间
- startTime, err := time.Parse("15:04", cw.Start)
- if err != nil {
- fmt.Println("云端配置文件解析采集时间【startTime】失败 ", err, "取默认值【00:00】")
- cw.StartTime, _ = time.Parse("15:04", "00:00")
- }
- cw.StartTime = startTime
- endTime, err := time.Parse("15:04", cw.End)
- if err != nil {
- fmt.Println("云端配置文件解析采集时间【endTime】失败 ", err, "取默认值【23:59】")
- cw.EndTime, _ = time.Parse("15:04", "23:59")
- }
- cw.EndTime = endTime
- if len(cw.Days) == 0 {
- // 默认设置为每天
- cw.Days = []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
- }
- // todo 待测逻辑
- if cw.Flag == 0 { // 关闭固定时间段采集, 则都返回true
- fmt.Println("已关闭采集时间段限制")
- return true
- }
- if len(cw.Days) > 0 { // 如果指定了周几
- currentDay := currentTime.Weekday().String()
- fmt.Println("currentDay", currentDay)
- included := false
- for _, day := range cw.Days {
- if day == currentDay {
- fmt.Println("当前时间符合规定的日期要求")
- included = true
- break
- }
- }
- if !included {
- fmt.Println("当前时间不符合规定的日期要求")
- return false
- }
- }
- start := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), cw.StartTime.Hour(), cw.StartTime.Minute(), cw.StartTime.Second(), 0, currentTime.Location())
- end := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), cw.EndTime.Hour(), cw.EndTime.Minute(), cw.EndTime.Second(), 0, currentTime.Location())
- fmt.Println("start", start)
- fmt.Println("end", end)
- if start.After(end) { // 如果时段跨天
- end = end.AddDate(0, 0, 1)
- fmt.Println("当前时间设置的时间段跨天,更正end时间", end)
- }
- return !currentTime.Before(start) && currentTime.Before(end)
- }
- func main() {
- flag := IsTimeAllowed(time.Now())
- if flag {
- fmt.Println("当前时间段符合规定,允许采集")
- } else {
- fmt.Println("当前时间段不符合规定,不允许采集")
- }
- }
|