时区转换为偏移量?

huangapple go评论99阅读模式
英文:

TimeZone to Offset?

问题

我想要从指定的时区获取偏移量(以秒为单位)。这正是Perl的Time::Zone中的tz_offset()所做的:"确定指定时区相对于GMT的偏移量(以秒为单位)"。

在Go语言中是否已经有一种方法可以实现这个功能?输入是一个只包含时区名称的字符串,但我知道Go语言的time包中有LoadLocation()函数,所以字符串 => 偏移量位置 => 偏移量都可以。

输入: "MST"

输出: -25200

英文:

I want to get the offset in seconds from a specified time zone. That is exactly what tz_offset() in Perl's Time::Zone does: "determines the offset from GMT in seconds of a specified timezone".

Is there already a way of doing this in Go? The input is a string that has the time zone name and that's it, but I know that Go has LoadLocation() in the time package, so string => offset or location => offset should be fine.

Input: "MST"

Output: -25200

答案1

得分: 4

这应该能解决问题:

location, err := time.LoadLocation("MST")
if err != nil {
	panic(err)
}

tzName, tzOffset := time.Now().In(location).Zone()

fmt.Printf("name: [%v]\toffset: [%v]\n", tzName, tzOffset)

将打印出:

name: [MST] offset: [-25200]

Go Playground: https://play.golang.org/p/GVTgnpe1mB1

英文:

This should do the trick:

location, err := time.LoadLocation("MST")
if err != nil {
	panic(err)
}

tzName, tzOffset := time.Now().In(location).Zone()

fmt.Printf("name: [%v]\toffset: [%v]\n", tzName, tzOffset)

Will print:

>name: [MST] offset: [-25200]

Go Playground: https://play.golang.org/p/GVTgnpe1mB1

答案2

得分: 0

这是计算本地时区和指定时区之间当前偏移量的代码。我同意Ainar-G的评论,偏移量只在与指定的时间点相关时才有意义:

package main

import (
	"fmt"
	"time"
)

func main() {
	loc, err := time.LoadLocation("MST")
	if err != nil {
		fmt.Println(err)
	}

	now := time.Now()
	_, destOffset := now.In(loc).Zone()
	_, localOffset := now.Zone()

	fmt.Println("偏移量:", destOffset-localOffset)
}
英文:

Here is the code, that calculates current offset between local and specified timezones. I agree with Ainar-G's comment that offset makes sense only with relation to specified moment in time:

package main

import (
	"fmt"
	"time"
)

func main() {
	loc, err := time.LoadLocation("MST")
	if err != nil {
		fmt.Println(err)
	}

	now := time.Now()
	_, destOffset := now.In(loc).Zone()
	_, localOffset := now.Zone()

	fmt.Println("Offset:", destOffset-localOffset)
}

huangapple
  • 本文由 发表于 2016年1月27日 20:07:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/35036951.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定