Golang 中按週數排列的日期範圍
背景:
背景:背景:
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 }
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))
取得日期範圍,決定一週的第一天並新增 6天以獲得最後一天
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
範例:
輸出(在 Go Playground上試):附加說明:WeekStart()函數管理超出範圍的週。年份範圍之外的周分別解釋為上一年或下一年的最後一周或第一週。以上是如何在 Golang 中計算給定週數的日期範圍?的詳細內容。更多資訊請關注PHP中文網其他相關文章!