-
Notifications
You must be signed in to change notification settings - Fork 0
/
hour_unit_expression.go
executable file
·113 lines (99 loc) · 2.18 KB
/
hour_unit_expression.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package timeexpression
import (
"errors"
"strings"
)
// hourUnitExpression 小时/分钟/秒的最小解析单位
type hourUnitExpression struct {
start hourUnit
end hourUnit
isAll bool
}
// newHourUnitExpression 格式为 *,hh:mm:ss-hh:mm:ss
func newHourUnitExpression(unitStr string) (*hourUnitExpression, error) {
unitStr = strings.Trim(unitStr, " ")
if unitStr == "*" {
expression := &hourUnitExpression{
start: hourUnit{
Hour: 0,
Minute: 0,
Sec: 0,
},
end: hourUnit{
Hour: 24,
Minute: 0,
Sec: 0,
},
}
expression.isAll = true
return expression, nil
}
expression := &hourUnitExpression{}
hourSubList := strings.Split(unitStr, "-")
if len(hourSubList) != 2 {
// 表达式为00:00:00-24:00:00,必须分为2段
return nil, ErrHourUnitFormat
}
var err error
// 处理开始时间
expression.start, err = newHourTimeUnit(hourSubList[0])
if err != nil {
return nil, err
}
// 处理结束时间
expression.end, err = newHourTimeUnit(hourSubList[1])
if err != nil {
return nil, err
}
err = expression.check()
if err != nil {
return nil, err
}
return expression, nil
}
// check 检查参数是否正确
func (expression *hourUnitExpression) check() error {
startSec := expression.start.toSec()
endSec := expression.end.toSec()
if startSec >= endSec {
return errors.New("hour error: start after end")
}
return nil
}
// isIn 是否在表达式范围内
func (expression *hourUnitExpression) isIn(hour, minute, sec int) bool {
// 检验小时
if hour < expression.start.Hour || hour > expression.end.Hour {
return false
}
if hour > expression.start.Hour && hour < expression.end.Hour {
return true
}
if hour == expression.start.Hour {
// 小时等于开始
if minute < expression.start.Minute {
return false
}
if minute > expression.start.Minute {
return true
}
// 分钟相等,判断秒
if sec < expression.start.Sec {
return false
}
return true
} else {
// 小时等于结束
if minute > expression.end.Minute {
return false
}
if minute < expression.end.Minute {
return true
}
// 分钟相等,判断秒
if sec >= expression.end.Sec {
return false
}
return true
}
}