-
Notifications
You must be signed in to change notification settings - Fork 1
/
calendarweek.go
53 lines (43 loc) · 1.18 KB
/
calendarweek.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
package main
import (
"time"
"github.com/snabb/isoweek"
)
type CalendarWeekIterator struct {
ChangedCh chan int
}
func currentCalendarWeekIterator() CalendarWeekIterator {
return calendarWeekIteratorWithCustomProvider(10*time.Minute, currentIsoWeek)
}
func currentIsoWeek() int {
_, currentWeekNumber := time.Now().ISOWeek()
return currentWeekNumber
}
func calendarWeekIteratorWithCustomProvider(duration time.Duration, currentWeekProvider func() int) CalendarWeekIterator {
ch := make(chan int)
go func() {
var lastWeekNumber = -1
for ticker := time.NewTicker(duration); ; <-ticker.C {
currentWeekNumber := currentWeekProvider()
if lastWeekNumber != currentWeekNumber {
lastWeekNumber = currentWeekNumber
ch <- currentWeekNumber
}
}
}()
return CalendarWeekIterator{ch}
}
func offsetCalendarWeekToDate(idx int) (int, time.Time) {
return offsetCalendarWeekToDateFromDate(idx, time.Now())
}
func offsetCalendarWeekToDateFromDate(idx int, offset time.Time) (int, time.Time) {
year, week := offset.ISOWeek()
for i := 0; i < idx; i++ {
week++
if !isoweek.Validate(year, week) {
week = 1
year++
}
}
return week, isoweek.StartTime(year, week, time.Local)
}