← 中文资源

简体中文版本

Time Date 归一化越界字段

用越界字段构造时间,交给 time.Date 归一化:第 0 天、第 14 个月、负纳秒都会被换算成真实时刻而不是报错。

阅读英文原文

实现说明

Time Date 归一化越界字段可以归结为函数 main。

使用要点

  • 跑完文件,输出里会留下标记——day 0:、month 14:、hour 25 minute 61:。

常见问题

运行「Time Date 归一化越界字段」会打印什么?

整个文件跑完,输出行以 day 0:、month 14:、hour 25 minute 61: 这类前缀开头。

核心语句

lateHour := time.Date(2026, time.January, 2, 25, 61, 0, 0, time.UTC)

代码示例

package main

import (
	"fmt"
	"time"
)

func main() {
	// time.Date normalizes overflow fields instead of failing
	rollover := time.Date(2026, time.March, 0, 12, 0, 0, 0, time.UTC)
	fmt.Println("day 0:", rollover.Format("2006-01-02"))

	month14 := time.Date(2026, time.Month(14), 1, 0, 0, 0, 0, time.UTC)
	fmt.Println("month 14:", month14.Format("2006-01-02"))

	lateHour := time.Date(2026, time.January, 2, 25, 61, 0, 0, time.UTC)
	fmt.Println("hour 25 minute 61:", lateHour.Format("2006-01-02 15:04"))

	// negative nanoseconds move the instant backwards
	negative := time.Date(2026, time.January, 1, 0, 0, 0, -1, time.UTC)
	fmt.Println("nanos -1:", negative.Format("2006-01-02 15:04:05.999999999"))

	// day 0 of a month is the last day of the previous month
	start := time.Date(2026, time.February, 1, 0, 0, 0, 0, time.UTC)
	fmt.Println("jan end:", start.AddDate(0, 0, -1).Format("2006-01-02"))
}