Parsing time offset in Go using time package

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

Parsing time offset in Go using time package

问题

我正在尝试使用Go语言中的Time包来提取时间详细信息。我已经成功解析了年、月、日、小时、分钟和秒等数值。但是,当我尝试使用Zone来提取偏移量时,我似乎得到了一个错误的偏移量。

当我尝试查看我的Time对象时,我发现有两个偏移量条目,不确定我做错了什么。

以下是代码和输出:

serverTime := "2021-10-31T22:17:03.996-0700"
fmt.Println("Server time is: ", serverTime)
t, _ := time.Parse("2006-01-02T15:04:05.999-0700", serverTime)
zone, offset := t.Zone()
fmt.Println("Printing time object: ", t)
fmt.Println("Year", t.Year())
fmt.Println("Month", t.Month().String())
fmt.Println("Date", t.Day())
fmt.Println("Hour", t.Hour())
fmt.Println("Minutes", t.Minute())
fmt.Println("Seconds", t.Second())

fmt.Println("Zone:", zone)
fmt.Println("Offset", offset)

偏移量的输出为:
Offset -25200
而我期望它是 -0700

这是playground的链接。

英文:

I am trying to use Time package in Go to extract the time details as under. I have been able to successfully parse values such as year, month, date, hour, minutes and seconds. Unfortunately, when I try to use Zone to extract offset, I seem to be getting an incorrect offset.

When I tried to view my Time object, I see two entries for offset, not sure what am I doing incorrectly.

 serverTime := "2021-10-31T22:17:03.996-0700"
	fmt.Println("Server time is: ", serverTime)
	t, _ := time.Parse("2006-01-02T15:04:05.999-0700", serverTime)
	zone, offset := t.Zone()
	fmt.Println("Printing time object: ",t)
	fmt.Println("Year", t.Year())
	fmt.Println("Month", t.Month().String())
	fmt.Println("Date", t.Day())
	fmt.Println("Hour", t.Hour())
	fmt.Println("Minutes", t.Minute())
	fmt.Println("Seconds",t.Second())

	fmt.Println("Zone:", zone)
	fmt.Println("Offset", offset)

The output that is see for offset is:
Offset -25200
and I expect it to be -0700

Here is the link to playground

答案1

得分: 4

func(Time) Zone 返回第二个参数 offset,它表示相对于UTC的秒数。因此,你的偏移量 -0700 被返回为 -25200,即 - (7 * 60 * 60)。

英文:

The func(Time) Zone returns the second argument offset which is the seconds east of UTC. So your offset of -0700 is returned as -25200 which is - (7 * 60 * 60)

huangapple
  • 本文由 发表于 2021年11月1日 13:41:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/69793019.html
匿名

发表评论

匿名网友

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

确定