forked from miku/metha
-
Notifications
You must be signed in to change notification settings - Fork 0
/
intervals.go
57 lines (51 loc) · 1.22 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
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
}