在Go中,如何提取当前本地时间偏移的值?

时间:2016-01-24 11:08:05

标签: go timezone-offset

我是Go新手,我正在努力格式化并显示一些IBM大型机TOD时钟数据。我想格式化GMT和本地时间的数据(作为默认值 - 否则在用户指定的区域中。)

为此,我需要将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)
}

有没有简单的方法来获取此信息?

3 个答案:

答案 0 :(得分:18)

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

package main

import (
    "fmt"
    "time"
)

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

区域计算在时间t生效的时区,返回区域的缩写名称(例如“CET”)及其在UTC以东的秒数。

答案 1 :(得分:8)

  

Package time

     

func (Time) Local

func (t Time) Local() Time
     

本地返回t,位置设置为当地时间。

     

func (Time) Zone

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

区域计算在时间t生效的时区,返回   区域的缩写名称(例如“CET”)及其以秒为单位的偏移量   UTC以东。

     

type Location

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

位置将时间映射映射到当时正在使用的区域。   通常,Location表示时间偏移的集合   用于中欧的CEST和CET等地理区域。

var Local *Location = &localLoc
     

Local表示系统的本地时区。

var UTC *Location = &utcLoc
     

UTC代表通用协调时间(UTC)。

     

func (Time) In

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

在返回t中,位置信息设置为loc。

     

如果loc为零,恐慌。

例如,

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

答案 2 :(得分:4)

我认为手动将时间转换为另一个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))
}
相关问题