Date Range by Week Number in Go
Given the week number obtained using the provided Week function, this article explores how to determine the corresponding date range starting on Sunday.
Foreword: ISO Week and Custom Handling
It's important to note that the standard ISO Week starts on Monday. To adapt to this convention, the following approach handles weeks starting on either Monday or Sunday.
Week Range Determination
To determine the date range of a week, we:
Implementation:
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 }
Example Usage:
fmt.Println(WeekStart(2018, 1)) // Output: 2018-01-01 00:00:00 +0000 UTC fmt.Println(WeekStart(2018, 2)) // Output: 2018-01-08 00:00:00 +0000 UTC
Handling Out-of-Range Weeks:
This implementation handles out-of-range weeks gracefully, interpreting them as weeks of the previous or next year.
Determining End of Week:
To obtain the last day of the week, simply add 6 days to the week's first day:
func WeekRange(year, week int) (start, end time.Time) { start = WeekStart(year, week) end = start.AddDate(0, 0, 6) return }
The above is the detailed content of How to Calculate the Date Range for a Given Week Number in Go?. For more information, please follow other related articles on the PHP Chinese website!