Fixed Offset Time Zones With FixedZone

Render the same instant in UTC, a plus-eight zone, and a minus-five-thirty zone without an IANA database, then format a parsed offset back with Z07:00.

GoConfig Management

Code

gosnippet
24 lines
package main

import (
	"fmt"
	"time"
)

func main() {
	// 无 IANA 数据库依赖的固定偏移时区:东八区与西五点半
	utcPlus8 := time.FixedZone("UTC+8", 8*3600)
	utcMinus530 := time.FixedZone("UTC-5:30", -5*3600-30*60)

	t := time.Date(2026, 11, 19, 12, 0, 0, 0, time.UTC)
	fmt.Println("UTC     :", t.Format(time.RFC3339))
	fmt.Println("in +8   :", t.In(utcPlus8).Format(time.RFC3339))
	fmt.Println("in -5:30:", t.In(utcMinus530).Format(time.RFC3339))

	// 解析带偏移的时间串,偏移随值保留而不是落到本地时区
	parsed, err := time.Parse(time.RFC3339, "2026-11-19T12:00:00+08:00")
	if err != nil {
		panic(err)
	}
	fmt.Println("parsed  :", parsed.Format("2006-01-02 15:04:00 Z07:00"))
}

Zones built without an IANA database

time.FixedZone("UTC+8", 8*3600) and time.FixedZone("UTC-5:30", -5*3600-30*60) construct named zones from raw offsets in seconds — no tzdata lookup, useful for fixed-offset protocols. One instant, time.Date(2026, 11, 19, 12, 0, 0, 0, time.UTC), is then rendered three ways with t.In(zone).Format(time.RFC3339).

The same instant in three offsets

UTC     : 2026-11-19T12:00:00Z
in +8   : 2026-11-19T20:00:00+08:00
in -5:30: 2026-11-19T06:30:00-05:30
parsed  : 2026-11-19 12:00:00 +08:00

The first three lines are one time.Time printed in UTC, plus-eight, and minus-five-thirty; only the offset and the wall clock move. The fourth line parses "2026-11-19T12:00:00+08:00" with time.Parse(time.RFC3339, …) and formats it back with layout "2006-01-02 15:04:00 Z07:00" — the Z07:00 verb reproduces the offset the parsed value carried, instead of dropping it to local time.

The line that keeps the offset

parsed, err := time.Parse(time.RFC3339, "2026-11-19T12:00:00+08:00")
if err != nil {
	panic(err)
}

A value parsed with an explicit offset retains that fixed zone internally, which is what lets the final Format round-trip +08:00 exactly.

Interactive Tools for This Topic

FAQ

What is the error handling style?
The failure path is `panic(err)` — detected problems halt the run rather than being passed back.
What does Fixed Offset Time Zones With FixedZone print when run?
No setup needed: run the file and look for labeled lines like `UTC :`, `in +8 :`, `in -5:30:` in the output.