-
Notifications
You must be signed in to change notification settings - Fork 5
/
goweek.go
94 lines (80 loc) · 2.09 KB
/
goweek.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
package goweek
import (
"errors"
"time"
)
// A Week is a main package data type
type Week struct {
Days []time.Time
Year int
Number int
}
// NewWeek constructs new Week entity from given parameters (year and ISO-8601-compatible week number)
func NewWeek(params ...int) (*Week, error) {
if len(params) < 2 {
return &Week{}, errors.New("NewWeek(): too few arguments, specify year and number of week")
} else if params[0] < 0 {
return &Week{}, errors.New("NewWeek(): year can't be less than zero")
} else if params[1] < 1 || params[1] > 53 {
return &Week{}, errors.New("NewWeek(): number of week can't be less than 1 or greater than 53")
}
var (
week = initWeek(params...)
day = 1
fd = time.Date(week.Year, 1, day, 0, 0, 0, 0, time.UTC)
y, w = fd.ISOWeek()
)
for y != week.Year && w > 1 {
day++
fd = time.Date(week.Year, 1, day, 0, 0, 0, 0, time.UTC)
y, w = fd.ISOWeek()
}
// getting Monday of the 1st week
for fd.Weekday() > 1 {
day--
fd = time.Date(week.Year, 1, day, 0, 0, 0, 0, time.UTC)
}
// getting first day of the given week
fd = fd.AddDate(0, 0, (week.Number-1)*7)
for fd.Year() > y {
fd = fd.AddDate(0, 0, -7)
}
// getting dates for whole week
for i := 0; i < 7; i++ {
week.Days = append(week.Days, fd.Add(time.Duration(i)*24*time.Hour))
}
return &week, nil
}
// Next calculates and returns information (year, week number and dates) about next week
func (week *Week) Next() (*Week, error) {
var newYear, newWeek int
if week.Number+1 > 53 {
newYear = week.Year + 1
newWeek = 1
} else {
newYear = week.Year
newWeek = week.Number + 1
}
w, e := NewWeek(newYear, newWeek)
return w, e
}
// Previous calculates and returns information (year, week number and dates) about previous week
func (week *Week) Previous() (*Week, error) {
var newYear, newWeek int
if week.Number-1 < 1 {
newYear = week.Year - 1
newWeek = 53
} else {
newYear = week.Year
newWeek = week.Number - 1
}
w, e := NewWeek(newYear, newWeek)
return w, e
}
func initWeek(params ...int) Week {
var week = Week{
Year: params[0],
Number: params[1],
}
return week
}