← 中文资源

简体中文版本

Time ZoneBounds DST 时间跨度

用 Time.ZoneBounds 查询某个时刻所在时区的起止边界,观察夏令时切换把一年切成两段偏移不同的时间跨度。

阅读英文原文

实现说明

Time ZoneBounds DST 时间跨度以函数 main为骨架。 没有静默穿透——中途有 1 个检查点测试 err != nil。

使用要点

  • 演示输出是带标签的(location failed:、instant:、zone name:),每个操作都会留下自己的一行标注。

常见问题

运行「Time ZoneBounds DST 时间跨度」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 location failed:、instant:、zone name: 这类标签。

核心语句

if err != nil {
	fmt.Println("location failed:", err)
	return
}

代码示例

package main

import (
	"fmt"
	"time"
	_ "time/tzdata"
)

func main() {
	loc, err := time.LoadLocation("America/New_York")
	if err != nil {
		fmt.Println("location failed:", err)
		return
	}

	// daylight-saving (DST) starts on the second Sunday of March in 2026
	dst := time.Date(2026, time.March, 8, 3, 30, 0, 0, loc)
	start, end := dst.ZoneBounds()
	fmt.Println("instant:", dst.Format(time.RFC3339))
	fmt.Println("zone name:", dst.Format("MST"))
	fmt.Println("zone starts:", start.Format(time.RFC3339))
	fmt.Println("zone ends:", end.Format(time.RFC3339))

	// a winter instant falls into the other span of the same location
	winter := time.Date(2026, time.December, 1, 12, 0, 0, 0, loc)
	wStart, wEnd := winter.ZoneBounds()
	fmt.Println("winter zone:", winter.Format("MST"))
	fmt.Println("winter starts:", wStart.Format(time.RFC3339))
	fmt.Println("winter ends:", wEnd.Format(time.RFC3339))
}