如何提取当前本地时间偏移的值?

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

我在尝试格式化和显示一些 IBM 大型机 TOD 时钟数据时遇到了一些困难。我想在格林威治标准时间和本地时间中格式化数据(作为默认设置 - 否则在用户指定的区域中)。

为此,我需要获取与 GMT 的本地时间偏移值作为有符号整数秒数。

在zoneinfo.go中(我承认我并不完全理解),我可以看到

// 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?
}

但我认为这不是导出的,所以这段代码不起作用:

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

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

是否有获取此信息的简单方法?

您可以在时间类型上使用 Zone() 方法:

package main

import (
    "fmt"
    "time"
)

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

Zone 计算在时间 t 生效的时区,返回时区的缩写名称(例如 "CET")及其在 UTC 以东的秒数偏移量。

Package time

func (Time) Local

func (t Time) Local() Time

Local returns t with the location set to local time.

func (Time) Zone

func (t Time) Zone() (name string, offset int)

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.

type Location

type Location struct {
        // contains filtered or unexported fields
}

A Location maps time instants to the zone in use at that time. Typically, the Location represents the collection of time offsets in use in a geographical area, such as CEST and CET for central Europe.

var Local *Location = &localLoc

Local represents the system's local time zone.

var UTC *Location = &utcLoc

UTC represents Universal Coordinated Time (UTC).

func (Time) In

func (t Time) In(loc *Location) Time

In returns t with the location information set to loc.

In panics if loc is nil.

例如,

package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Now()

    // For a time t, offset in seconds east of UTC (GMT)
    _, offset := t.Local().Zone()
    fmt.Println(offset)

    // For a time t, format and display as UTC (GMT) and local times.
    fmt.Println(t.In(time.UTC))
    fmt.Println(t.In(time.Local))
}

输出:

-18000
2016-01-24 16:48:32.852638798 +0000 UTC
2016-01-24 11:48:32.852638798 -0500 EST

我认为手动将时间转换为另一个 TZ 没有意义。使用time.Time.In函数:

package main

import (
    "fmt"
    "time"
)

func printTime(t time.Time) {
    zone, offset := t.Zone()
    fmt.Println(t.Format(time.Kitchen), "Zone:", zone, "Offset UTC:", offset)
}

func main() {
    printTime(time.Now())
    printTime(time.Now().UTC())

    loc, _ := time.LoadLocation("America/New_York")
    printTime(time.Now().In(loc))
}