package tracking import ( "fmt" "regexp" "strconv" "time" ) const ( dayKeyLayout = "2006-01-02" weekKeyFmt = "%d-W%02d" ) var weekKeyPattern = regexp.MustCompile(`^(\d{4})-W(\d{2})$`) // WeekKeyForDayKey returns the ISO week key (YYYY-Www) of a day key (YYYY-MM-DD). // It returns an empty string when the day key is invalid. func WeekKeyForDayKey(dayKey string) string { t, err := time.Parse(dayKeyLayout, dayKey) if err != nil { return "" } year, week := t.ISOWeek() return fmt.Sprintf(weekKeyFmt, year, week) } // WeekDayKeys returns the day keys (YYYY-MM-DD) of Monday to Sunday of the ISO week // weekKey (YYYY-Www). It returns ErrInvalidWeekKey for a malformed week key and // for a week the year does not have, for example 2025-W53. func WeekDayKeys(weekKey string) ([]string, error) { m := weekKeyPattern.FindStringSubmatch(weekKey) if m == nil { return nil, ErrInvalidWeekKey } year, _ := strconv.Atoi(m[1]) week, _ := strconv.Atoi(m[2]) if week < 1 || week > 53 { return nil, ErrInvalidWeekKey } // Jan 4 is always in week 1 of its year. jan4 := time.Date(year, time.January, 4, 0, 0, 0, 0, time.UTC) _, jan4Week := jan4.ISOWeek() // (weekday+6)%7 counts the days since Monday (Mon=0, Sun=6). daysSinceMonday := int(jan4.Weekday()+6) % 7 monday := jan4.AddDate(0, 0, -daysSinceMonday+(week-jan4Week)*7) keys := make([]string, 7) for i := range keys { keys[i] = monday.AddDate(0, 0, i).Format(dayKeyLayout) } // Every year has 52 ISO weeks, but only some have a 53rd one. Without this // check the days of the following W01 would be closed under a second key. if WeekKeyForDayKey(keys[0]) != weekKey { return nil, ErrInvalidWeekKey } return keys, nil } func validDayKey(dayKey string) bool { _, err := time.Parse(dayKeyLayout, dayKey) return err == nil } func parseDayKey(dayKey string) time.Time { t, _ := time.Parse(dayKeyLayout, dayKey) return t } func endOfDayMs(dayKey string, loc *time.Location) (int64, error) { t, err := time.Parse(dayKeyLayout, dayKey) if err != nil { return 0, err } end := time.Date(t.Year(), t.Month(), t.Day(), 23, 59, 59, 999_000_000, loc) return end.UnixMilli(), nil }