AddDate Normalizes Overflowing Month Days
AddDate rolls overflowing days into the next month, so January 31 plus one month lands in March; clamp with day zero to stay at month end.
Code
package main
import (
"fmt"
"time"
)
func main() {
billing := time.Date(2026, time.January, 31, 12, 0, 0, 0, time.UTC)
// 1 月 31 日 + 1 个月 = 2 月 31 日,不存在
// AddDate 把溢出的天数顺延到下个月:得到 3 月 3 日(2026 非闰年)
fmt.Println("rolled:", billing.AddDate(0, 1, 0).Format("2006-01-02"))
// 想停在 2 月底:取“3 月的第 0 天”,Go 规范化为 2 月最后一天
clamp := time.Date(2026, time.March, 0, 12, 0, 0, 0, time.UTC)
fmt.Println("clamped:", clamp.Format("2006-01-02"))
// 闰年同样成立:2024 年 2 月有 29 天
leap := time.Date(2024, time.March, 0, 12, 0, 0, 0, time.UTC)
fmt.Println("leap:", leap.Format("2006-01-02"))
}The overflow roll
AddDate works on calendar months. January 31 plus one month asks for February 31, which does not exist in 2026, so the day overflow rolls forward and the run prints 2026-03-03 — March 3, not the end of February.
Clamping with day zero
To land at month end, the snippet builds time.Date(2026, time.March, 0, …) — day zero normalizes to the last day of the previous month, so the clamped value prints 2026-02-28.
Leap-year note
The same trick prints 2024-02-29 for the 2024 date because February had 29 days that year; the normalization follows the real calendar rather than a fixed 30-day month.
Interactive Tools for This Topic
FAQ
- Why does January 31 plus one month give March 3?
- February 31 does not exist; AddDate normalizes the overflow by rolling the extra days forward into March, producing March 3 in a non-leap year.
- How does day zero clamp to month end?
- time.Date normalizes out-of-range fields; day 0 of a month resolves to the last day of the previous month, which is exactly the clamp the demo relies on.
Report a problem with this exampleOpens a pre-filled issue on GitHub.