-
Notifications
You must be signed in to change notification settings - Fork 13
/
intervals.go
76 lines (69 loc) · 1.68 KB
/
intervals.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
package metha
import (
"fmt"
"time"
"github.com/jinzhu/now"
)
// Interval represents a span of time.
type Interval struct {
Begin time.Time
End time.Time
}
// String formats the interval.
func (iv Interval) String() string {
return fmt.Sprintf("[%s--%s]", iv.Begin, iv.End)
}
// MonthlyIntervals segments a given interval into monthly intervals.
func (iv Interval) MonthlyIntervals() []Interval {
var ivals []Interval
start := iv.Begin
for {
if start.After(iv.End) {
break
}
end := now.New(start).EndOfMonth()
if end.After(iv.End) {
ivals = append(ivals, Interval{Begin: start, End: iv.End})
break
}
ivals = append(ivals, Interval{Begin: start, End: end})
start = now.New(start.AddDate(0, 1, 0)).BeginningOfMonth()
}
return ivals
}
// DailyIntervals segments a given interval into daily intervals.
func (iv Interval) DailyIntervals() []Interval {
var ivals []Interval
start := iv.Begin
for {
if start.After(iv.End) {
break
}
end := now.New(start).EndOfDay()
if end.After(iv.End) {
ivals = append(ivals, Interval{Begin: start, End: end})
break
}
ivals = append(ivals, Interval{Begin: start, End: end})
start = now.New(start.AddDate(0, 0, 1)).BeginningOfDay()
}
return ivals
}
// HourlyIntervals segments a given interval into hourly intervals.
func (iv Interval) HourlyIntervals() []Interval {
var ivals []Interval
start := iv.Begin
for {
if start.After(iv.End) {
break
}
end := now.New(start).EndOfHour()
if end.After(iv.End) {
ivals = append(ivals, Interval{Begin: start, End: end})
break
}
ivals = append(ivals, Interval{Begin: start, End: end})
start = now.New(start.Add(time.Hour * 1)).BeginningOfHour()
}
return ivals
}