Handle DST and Unix timestamps
Handle DST and Unix timestamps
A Unix timestamp counts seconds since 1970-01-01 00:00:00 UTC, independently of display zone. UnixMilli and UnixMicro use different units. Daylight saving time (DST) transitions can create local clock readings that occur twice or never occur. Use an explicit offset to distinguish repeated readings and validate the named zone if the business contract requires it.
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) a, e := time.Parse(time.RFC3339, "2024-11-03T01:30:00-04:00") check(e) b, e := time.Parse(time.RFC3339, "2024-11-03T01:30:00-05:00") check(e) fmt.Println(a.In(loc).IsDST(), b.In(loc).IsDST()) fmt.Println(b.Unix() - a.Unix()) fmt.Println(a.Equal(b))}The two historical readings have the same local clock fields but different offsets and are one hour apart. Parse the numeric offset first, then convert to the named location and verify the expected offset and clock fields if both were supplied. Date and ParseInLocation alone do not guarantee which side of an ambiguous transition is selected; do not rely on a particular answer. A spring-gap time needs an explicit reject or adjustment policy.
Expected output:
true false3600falseKeep epoch units explicit
package main
import ( "fmt" "time")
func main() { t := time.UnixMilli(1500).UTC() fmt.Println(t.Format("2006-01-02T15:04:05.000Z07:00")) fmt.Println(t.Unix(), t.UnixMilli(), t.UnixMicro())}The value 1500 milliseconds is one and a half seconds after the epoch. time.Unix(sec,nsec) takes seconds plus a nanosecond adjustment, not milliseconds. Document units at serialization boundaries; avoid guessing by digit count. UnixNano is only defined for times representable by int64 nanoseconds (roughly 1678–2262).
Expected output:
1970-01-01T00:00:01.500Z1 1500 1500000Try it locally
Convert 2500 Unix milliseconds into UTC and print using 2006-01-02T15:04:05.000Z07:00, then print UnixMilli again.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Time and scheduling 05: Handle DST and Unix timestamps
Check the lesson objective before moving on.
Why can two identical local clock readings represent different instants?
Which constructor accepts milliseconds since the Unix epoch?