-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
prev.go
57 lines (50 loc) · 1.59 KB
/
prev.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
package gronx
import (
"fmt"
"time"
)
// PrevTick gives previous run time before now
func PrevTick(expr string, inclRefTime bool) (time.Time, error) {
return PrevTickBefore(expr, time.Now(), inclRefTime)
}
// PrevTickBefore gives previous run time before given reference time
func PrevTickBefore(expr string, start time.Time, inclRefTime bool) (time.Time, error) {
gron, prev := New(), start.Truncate(time.Second)
due, err := gron.IsDue(expr, start)
if err != nil || (due && inclRefTime) {
return prev, err
}
segments, _ := Segments(expr)
if len(segments) > 6 && isUnreachableYear(segments[6], prev, true) {
return prev, fmt.Errorf("unreachable year segment: %s", segments[6])
}
prev, err = loop(gron, segments, prev, inclRefTime, true)
// Ignore superfluous err
if err != nil && gron.isDue(expr, prev) {
err = nil
}
return prev, err
}
func bumpReverse(ref time.Time, pos int) time.Time {
loc := ref.Location()
switch pos {
case 0:
ref = ref.Add(-time.Second)
case 1:
minTime := ref.Add(-time.Minute)
ref = time.Date(minTime.Year(), minTime.Month(), minTime.Day(), minTime.Hour(), minTime.Minute(), 59, 0, loc)
case 2:
hTime := ref.Add(-time.Hour)
ref = time.Date(hTime.Year(), hTime.Month(), hTime.Day(), hTime.Hour(), 59, 59, 0, loc)
case 3, 5:
dTime := ref.AddDate(0, 0, -1)
ref = time.Date(dTime.Year(), dTime.Month(), dTime.Day(), 23, 59, 59, 0, loc)
case 4:
ref = time.Date(ref.Year(), ref.Month(), 1, 0, 0, 0, 0, loc)
ref = ref.Add(-time.Second)
case 6:
yTime := ref.AddDate(-1, 0, 0)
ref = time.Date(yTime.Year(), 12, 31, 23, 59, 59, 0, loc)
}
return ref
}