Compare calendar and duration arithmetic
Compare calendar and duration arithmetic
AddDate changes calendar components in the time value’s location. Add advances by a fixed duration. A local calendar day need not contain exactly 24 elapsed hours; a month has no fixed duration. Choose the operation based on the requirement: tomorrow at the same local hour or exactly 24 hours later.
package main
import ( "fmt" "time")
func check(e error) { if e != nil { panic(e) }}
func main() { loc, e := time.LoadLocation("America/New_York") check(e) t := time.Date(2024, time.March, 9, 12, 0, 0, 0, loc) a := t.AddDate(0, 0, 1) b := t.Add(24 * time.Hour) fmt.Println(a.Format(time.RFC3339), a.Sub(t)) fmt.Println(b.Format(time.RFC3339), b.Sub(t))}The historical spring transition skips an hour. AddDate keeps noon in this example and only 23 hours pass. Add keeps the elapsed duration at 24 hours and arrives at 13:00. The named zone requires available zone data. Do not implement recurring local appointments by adding 24 hours repeatedly.
Expected output:
2024-03-10T12:00:00-04:00 23h0m0s2024-03-10T13:00:00-04:00 24h0m0sMonth ends need a policy
package main
import ( "fmt" "time")
func main() { t := time.Date(2024, time.January, 31, 9, 0, 0, 0, time.UTC) fmt.Println(t.AddDate(0, 1, 0).Format("2006-01-02")) last := time.Date(2024, time.March, 0, 9, 0, 0, 0, time.UTC) fmt.Println(last.Format("2006-01-02"))}January 31 plus one calendar month first forms February 31, which normalizes to March 2 in 2024. Day zero denotes the last day of the previous month. If billing requires clamping to the last day of the target month, implement that policy explicitly, rather than assuming AddDate clamps. Likewise, Truncate(24*time.Hour) is not a general local-midnight operation.
Expected output:
2024-03-022024-02-29Try it locally
Create the last day of February 2025 in UTC using March day zero. Print the date.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Time and scheduling 04: Compare calendar and duration arithmetic
Check the lesson objective before moving on.
Which operation models tomorrow at the same local clock reading when that reading exists uniquely?
Does AddDate always clamp the day to the last day of the target month?