2016-01-24 72 views
6

我是一个Go的新手,我努力尝试格式化和显示一些IBM大型机TOD时钟数据。我想在GMT和本地时间格式化数据(作为默认值 - 否则在用户指定的区域中)。在Go中,我如何提取当前本地时间偏移的值?

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

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

+0

@olif赢得,在一个非常近距离的事情。谢谢大家的答案。 –

回答

9

可以使用区()方法在时间类型:

package main 

import (
    "fmt" 
    "time" 
) 

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

区计算有效的时区在时间t,返回区的缩写名称(如“CET”)以及它在UTC以东秒的偏移量。

5

Package time

func (Time) Local

func (t Time) Local() Time 

本地回报吨,设定为当地时间的位置。

func (Time) Zone

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

区计算有效的时区在时间t,返回区域的 缩写名称(如“CET”)及其在几秒钟内偏移 东UTC的。

type Location

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

一个位置时刻映射到当时使用的区域。 典型地,位置表示在地理区域使用 时间偏移量的集合,例如中欧的CEST和CET。

var Local *Location = &localLoc 

本地代表系统的本地时区。

var UTC *Location = &utcLoc 

UTC代表世界协调时间(UTC)。

func (Time) In

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

在具有设置为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 
3

我不认为这是有道理的时间来手动转换到另一个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)) 
} 
相关问题