icz*_*cza 6
Time.ISOWeek()
标准库没有提供可以返回给定星期(年+周数)的日期范围的函数。因此,我们必须自己构建。
这并不难。我们可以从年中开始,与一周的第一天(星期一)对齐,获取该时间值的星期,然后修正:将与星期差乘以7的天数相加。
它看起来像这样:
func WeekStart(year, week int) time.Time {
// Start from the middle of the year:
t := time.Date(year, 7, 1, 0, 0, 0, 0, time.UTC)
// Roll back to Monday:
if wd := t.Weekday(); wd == time.Sunday {
t = t.AddDate(0, 0, -6)
} else {
t = t.AddDate(0, 0, -int(wd)+1)
}
// Difference in weeks:
_, w := t.ISOWeek()
t = t.AddDate(0, 0, (week-w)*7)
return t
}
测试它:
fmt.Println(WeekStart(2018, 1))
fmt.Println(WeekStart(2018, 2))
fmt.Println(WeekStart(2019, 1))
fmt.Println(WeekStart(2019, 2))
输出(在Go Playground上尝试):
2018-01-01 00:00:00 +0000 UTC
2018-01-08 00:00:00 +0000 UTC
2018-12-31 00:00:00 +0000 UTC
2019-01-07 00:00:00 +0000 UTC
WeekStart()0-1
WeekStart()
如果我们还需要最后一天:
func WeekRange(year, week int) (start, end time.Time) {
start = WeekStart(year, week)
end = start.AddDate(0, 0, 6)
return
}
测试它:
fmt.Println(WeekRange(2018, 1))
fmt.Println(WeekRange(2018, 2))
fmt.Println(WeekRange(2019, 1))
fmt.Println(WeekRange(2019, 2))
输出(在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