liveBook · Manning

Time

As explained in Learn Go with Pocket-Sized Projects

The time package is Go's standard-library package for measuring and displaying time and handling calendar-based calculations.

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

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains Add, AddDate, formatting layouts, locations, and boundary testing through a weekly-range implementation.
Examples
Uses a FormattedWeek type, midnight normalization, formatted layouts, and tests spanning weekdays, years, months, and time-zone changes.
What you can do after
Build it from scratch by calculating, testing, and formatting a weekly date range in Go.
How it connects
Connects durations, calendar arithmetic, weekdays, time zones, daylight saving time, and Go templates.

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.