gitee.com/quant1x/engine@v1.8.4/config/range_time.go (about) 1 package config 2 3 import ( 4 "fmt" 5 "gitee.com/quant1x/gox/exception" 6 "gitee.com/quant1x/pkg/yaml" 7 "regexp" 8 "strings" 9 "time" 10 ) 11 12 // 值范围正则表达式 13 var ( 14 stringRangePattern = "[~-]\\s*" 15 stringRangeRegexp = regexp.MustCompile(stringRangePattern) 16 ) 17 18 var ( 19 ErrTimeFormat = exception.New(errnoConfig+1, "时间格式错误") 20 formatOfTimestamp = time.TimeOnly 21 ) 22 23 func getTradingTimestamp() string { 24 now := time.Now() 25 return now.Format(formatOfTimestamp) 26 } 27 28 // TimeRange 时间范围 29 type TimeRange struct { 30 begin string // 开始时间 31 end string // 结束时间 32 } 33 34 func (this TimeRange) String() string { 35 return fmt.Sprintf("{begin: %s, end: %s}", this.begin, this.end) 36 } 37 38 func (this TimeRange) v2String() string { 39 return fmt.Sprintf("%s~%s", this.begin, this.end) 40 } 41 42 func (this *TimeRange) Parse(text string) error { 43 text = strings.TrimSpace(text) 44 arr := stringRangeRegexp.Split(text, -1) 45 if len(arr) != 2 { 46 return ErrTimeFormat 47 } 48 this.begin = strings.TrimSpace(arr[0]) 49 this.end = strings.TrimSpace(arr[1]) 50 if this.begin > this.end { 51 this.begin, this.end = this.end, this.begin 52 } 53 return nil 54 } 55 56 //// UnmarshalText 设置默认值调用 57 //func (this *TimeRange) UnmarshalText(text []byte) error { 58 // //TODO implement me 59 // panic("implement me") 60 //} 61 62 // UnmarshalYAML YAML自定义解析 63 func (this *TimeRange) UnmarshalYAML(node *yaml.Node) error { 64 var key, value string 65 if len(node.Content) == 0 { 66 value = node.Value 67 } else if len(node.Content) == 2 { 68 key = node.Content[0].Value 69 value = node.Content[1].Value 70 } 71 _ = key 72 return this.Parse(value) 73 } 74 75 func (this *TimeRange) IsTrading(timestamp ...string) bool { 76 var tm string 77 if len(timestamp) > 0 { 78 tm = strings.TrimSpace(timestamp[0]) 79 } else { 80 tm = getTradingTimestamp() 81 } 82 if tm >= this.begin && tm <= this.end { 83 return true 84 } 85 return false 86 }