ISOWeek Buckets Days Into Weeks

Bucket days into report weeks with ISOWeek, where Monday starts the week and year boundaries follow the ISO 8601 ownership rule.

GoData Integrity

Code

gosnippet
24 lines
package main

import (
	"fmt"
	"time"
)

// 报表按 ISO 周聚合:周一为一周起点,跨年归属也有标准答案
func bucket(day time.Time) string {
	year, week := day.ISOWeek()
	return fmt.Sprintf("%04d-W%02d", year, week)
}

func main() {
	days := []time.Time{
		time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC),   // 周四
		time.Date(2026, 1, 4, 0, 0, 0, 0, time.UTC),   // 周日,仍在同一周
		time.Date(2026, 1, 5, 0, 0, 0, 0, time.UTC),   // 周一,进入下一周
		time.Date(2025, 12, 29, 0, 0, 0, 0, time.UTC), // 年末,ISO 周属于 2026-W01
	}
	for _, day := range days {
		fmt.Printf("%s -> %s\n", day.Format(time.DateOnly), bucket(day))
	}
}

What the code does

ISOWeek Buckets Days Into Weeks keeps everything in the functions bucket and main.

The cycling part of this snippet is for _, day := range days.

What to watch for

  • Just the runtime — no packages to add, nothing to install.

Applying it

The definition doing the work: func bucket(day time.Time) string

Launch the file; main takes over and steps through bucket.

Statements doing the real work

return fmt.Sprintf("%04d-W%02d", year, week)
for _, day := range days {
	fmt.Printf("%s -> %s\n", day.Format(time.DateOnly), bucket(day))
}

Interactive Tools for This Topic

FAQ

How do you run ISOWeek Buckets Days Into Weeks?
Nothing to install first — run the file and the program does the rest.