How to Calculate the Start and End of a Day, Month, or Year in Go

Calculate start and end times for days, months, and years in Go using the time.Date method and duration arithmetic.

Use the time package's Date method to truncate a time.Time value to the start of a day, month, or year by setting the hour, minute, second, and nanosecond fields to zero.

import "time"

now := time.Now()
startOfDay := now.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
startOfMonth := now.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
startOfYear := now.Date(now.Year(), time.January, 1, 0, 0, 0, 0, now.Location())

endOfDay := startOfDay.Add(24 * time.Hour).Add(-1 * time.Nanosecond)
endOfMonth := startOfMonth.AddDate(0, 1, 0).Add(-1 * time.Nanosecond)
endOfYear := startOfYear.AddDate(1, 0, 0).Add(-1 * time.Nanosecond)

The Date method constructs a new time.Time with the specified year, month, day, and time components in the given location. To get the end of the period, add the appropriate duration (24 hours, 1 month, or 1 year) to the start time and subtract one nanosecond.