Use Go’s time package to calculate calendar periods, measure shorter durations, preserve time zones, and format timestamps for human-readable output. section 11.5.1
For a weekly date range, separate duration arithmetic from calendar arithmetic:
- Use Add for durations shorter than a day, such as subtracting one minute from a period’s end. section 11.5.1
- Use AddDate for changes beyond a day, such as moving between weeks, months, or years. section 11.5.1
- Build midnight values with the original location, then format them with a layout such as "02 January 2006". section 11.5.1
- Test dates across month and year boundaries, weekdays, non-UTC locations, and daylight-saving changes. section 11.5.1
A formatted week
Represent a week with start and end time.Time values. Begin at the included date’s midnight, move backward by its weekday using AddDate, then compute the end as seven days later minus one minute. Format both values through Start and End methods. section 11.5.1
Listing 11.36 week.go: New formatted week
// FormattedWeek defines ...
type FormattedWeek struct {
start, end time.Time #1
}
// NewFormattedWeek builds ...
func NewFormattedWeek(include time.Time, layout string) FormattedWeek {
start := startOfDay(include).
AddDate(0, 0, -int(include.Weekday())) #2
return FormattedWeek{
start: start,
end: start.AddDate(0, 0, 7).
Add(-1 * time.Minute), #3
layout: layout,
}
}
// startOfDay returns the same date as given, at midnight.
func startOfDay(t time.Time) time.Time {
year, month, day := t.Date()
return time.Date(year, month, day, 0, 0, 0, 0, t.Location())
}
Shows the complete weekly range construction, including location-preserving midnight calculation, AddDate, and the final Add operation. section 11.5.1
