Date Range by Week Number in Golang
Background:
Time.ISOWeek() returns the week number that starts on Monday. This article demonstrates how to obtain the date range for a given week, assuming it starts from Sunday.
Solution:
Start by aligning to the first day of the week (Monday) from the middle of the year. Corrigate by adding days based on the week difference multiplied by 7.
func WeekStart(year, week int) time.Time { t := time.Date(year, 7, 1, 0, 0, 0, 0, time.UTC) if wd := t.Weekday(); wd == time.Sunday { t = t.AddDate(0, 0, -6) } else { t = t.AddDate(0, 0, -int(wd)+1) } _, w := t.ISOWeek() t = t.AddDate(0, 0, (week-w)*7) return t }
To get the date range, determine the week's first day and add 6 days to obtain the last day.
func WeekRange(year, week int) (start, end time.Time) { start = WeekStart(year, week) end = start.AddDate(0, 0, 6) return }
Example:
fmt.Println(WeekRange(2018, 1)) fmt.Println(WeekRange(2018, 2)) fmt.Println(WeekRange(2019, 1)) fmt.Println(WeekRange(2019, 2))
Output (try it on the Go Playground):
2018-01-01 00:00:00 +0000 UTC 2018-01-07 00:00:00 +0000 UTC 2018-01-08 00:00:00 +0000 UTC 2018-01-14 00:00:00 +0000 UTC 2018-12-31 00:00:00 +0000 UTC 2019-01-06 00:00:00 +0000 UTC 2019-01-07 00:00:00 +0000 UTC 2019-01-13 00:00:00 +0000 UTC
Additional Note:
The WeekStart() function manages out-of-range weeks. Weeks outside the year range are interpreted as the last or first week of the previous or subsequent year, respectively.
The above is the detailed content of How to Calculate a Date Range Given a Week Number in Golang?. For more information, please follow other related articles on the PHP Chinese website!