How can I extract the value of my current local time offset?

Brent.Longborough picture Brent.Longborough · Jan 24, 2016 · Viewed 19.3k times · Source

I'm struggling a bit trying to format and display some IBM mainframe TOD clock data. I want to format the data in both GMT and local time (as the default -- otherwise in the zone the user specifies).

For this, I need to get the value of the local time offset from GMT as a signed integer number of seconds.

In zoneinfo.go (which I confess I don't fully understand), I can see

// A zone represents a single time zone such as CEST or CET.
type zone struct {
    name   string // abbreviated name, "CET"
    offset int    // seconds east of UTC
    isDST  bool   // is this zone Daylight Savings Time?
}

but this is not, I think, exported, so this code doesn't work:

package main
import ( "time"; "fmt" )

func main() {
    l, _ := time.LoadLocation("Local")
    fmt.Printf("%v\n", l.zone.offset)
}

Is there a simple way to get this information?

Answer

olif picture olif · Jan 24, 2016

You can use the Zone() method on the time type:

package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Now()
    zone, offset := t.Zone()
    fmt.Println(zone, offset)
}

Zone computes the time zone in effect at time t, returning the abbreviated name of the zone (such as "CET") and its offset in seconds east of UTC.