-
Notifications
You must be signed in to change notification settings - Fork 0
/
month_expression.go
executable file
·119 lines (101 loc) · 2.49 KB
/
month_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
114
115
116
117
118
119
package timeexpression
import (
"errors"
"strings"
"time"
)
func parseMonthInt(monthStr string) (int, error) {
month, err := time.Parse("01", monthStr)
if err != nil {
return 0, err
}
return int(month.Month()), nil
}
type monthExpression struct {
start int
end int
isAll bool
}
// newMonthExpression 创建月的时间表达式,支持格式为 [*,mm,mm-mm]
func newMonthExpression(expression string) (*monthExpression, error) {
monthExpression := &monthExpression{}
expression = strings.Trim(expression, " ")
if expression == "*" {
// *的情况
monthExpression.start = 1
monthExpression.end = 12
monthExpression.isAll = true
return monthExpression, nil
}
splitMonthStr := strings.Split(expression, "-")
if len(splitMonthStr) > 2 {
return nil, ErrMonthFormat
}
var err error
monthExpression.start, err = parseMonthInt(splitMonthStr[0])
if err != nil {
return nil, err
}
if len(splitMonthStr) == 2 {
monthExpression.end, err = parseMonthInt(splitMonthStr[1])
if err != nil {
return nil, err
}
} else {
monthExpression.end = monthExpression.start
}
err = monthExpression.check()
if err != nil {
return nil, err
}
return monthExpression, nil
}
func (expression *monthExpression) check() error {
if expression.start > expression.end {
return errors.New("month error: start after end")
}
return nil
}
// isIn 月份是否在周期内
func (expression *monthExpression) isIn(month int) bool {
if expression.start <= month && expression.end >= month {
return true
}
return false
}
// getStart 获取开始月
func (expression *monthExpression) getStart(month int) (start int, addYear bool, err error) {
idx := 1
addYear = false
for idx <= int(time.December) {
if expression.isIn(month) {
return expression.start, addYear, nil
}
month += 1
if month > int(time.December) {
month = 1
addYear = true
}
idx += 1
}
return 0, false, errors.New("monthExpression getStart get unreachable error")
}
// getEnd 获取结束月, 仅支持周期内
// 如果是"*"则结束月份返回12
// PS:如果年没有超出期限,则结束月为配置周期的结束月
func (expression *monthExpression) getEnd(month int) (end int, addYear bool, err error) {
idx := 1
addYear = false
for idx <= int(time.December) {
if expression.isIn(month) {
return expression.end, addYear, nil
}
month += 1
if month > int(time.December) {
month = 1
addYear = true
}
idx += 1
}
return 0, false, errors.New("monthExpression getEnd get unreachable error")
}