Bre*_*ugh 10 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?
}
Run Code Online (Sandbox Code Playgroud)
但我认为这不是导出的,所以这段代码不起作用:
package main
import ( "time"; "fmt" )
func main() {
l, _ := time.LoadLocation("Local")
fmt.Printf("%v\n", l.zone.offset)
}
Run Code Online (Sandbox Code Playgroud)
有没有一种简单的方法来获取这些信息?
oli*_*lif 19
您可以在时间类型上使用Zone()方法:
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
zone, offset := t.Zone()
fmt.Println(zone, offset)
}
Run Code Online (Sandbox Code Playgroud)
Zone计算在时间t生效的时区,返回区域的缩写名称(例如"CET")及其在UTC以东的秒数.
Run Code Online (Sandbox Code Playgroud)func (t Time) Local() Time本地返回t,位置设置为本地时间.
Run Code Online (Sandbox Code Playgroud)func (t Time) Zone() (name string, offset int)Zone计算在时间t生效的时区,返回区域的缩写名称(例如"CET")及其在UTC以东的秒数.
Run Code Online (Sandbox Code Playgroud)type Location struct { // contains filtered or unexported fields }位置将时间映射映射到当时正在使用的区域.通常,位置表示在地理区域中使用的时间偏移的集合,例如中欧的CEST和CET.
Run Code Online (Sandbox Code Playgroud)var Local *Location = &localLocLocal表示系统的本地时区.
Run Code Online (Sandbox Code Playgroud)var UTC *Location = &utcLocUTC表示通用协调时间(UTC).
Run Code Online (Sandbox Code Playgroud)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))
}
Run Code Online (Sandbox Code Playgroud)
输出:
-18000
2016-01-24 16:48:32.852638798 +0000 UTC
2016-01-24 11:48:32.852638798 -0500 EST
Run Code Online (Sandbox Code Playgroud)
我认为手动将时间转换为另一个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))
}
Run Code Online (Sandbox Code Playgroud)