在Go语言中,我们可以通过给定的地点名称来确定该地点的当前时间吗?

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

In Go, given a location name, how can we determine the current time in that location?

问题

我们不能使用Zone()返回的偏移量:

package main

import "fmt"
import "time"

func main() {
    loc, _ := time.LoadLocation("America/Los_Angeles")
    t := time.Date(2015,04,12,19,23,0,0,loc)
    t2 := time.Date(2015,03,1,19,23,0,0,loc)
    _, offset := t.Zone()
    _, offset2 := t.Zone()
    fmt.Printf("t1: %v  offset: %d\n", t, offset)
    fmt.Printf("t2: %v  offset: %d\n", t2, offset2)
}

这将返回:

t1: 2015-04-12 19:23:00 -0700 PDT  offset: -25200
t2: 2015-03-01 19:23:00 -0800 PST  offset: -25200

这个偏移量不反映夏令时。手动解析格式化时间实例后的偏移量(-0700和-0800)是唯一的选择吗?

我们可以使用time.Now()获取当前时间,但是使用.In()只是改变了位置,而没有调整小时和分钟。

英文:

We can't use the offset returned by Zone():

package main

import "fmt"
import "time"

func main() {
	loc, _ := time.LoadLocation("America/Los_Angeles")
	t := time.Date(2015,04,12,19,23,0,0,loc)
	t2 := time.Date(2015,03,1,19,23,0,0,loc)
	_, offset := t.Zone()
	_, offset2 := t.Zone()
	fmt.Printf("t1: %v  offset: %d\n", t, offset)
	fmt.Printf("t2: %v  offset: %d\n", t2, offset2)
}

This returns:

t1: 2015-04-12 19:23:00 -0700 PDT  offset: -25200
t2: 2015-03-01 19:23:00 -0800 PST  offset: -25200

The offset does not reflect daylight savings.
Is parsing manually the offset after formatting a time instance the only option (-0700 and -0800)?

We can retrieve the current time with time.Now(), but using .In() simply changes the location without adjusting the hours and minutes.

答案1

得分: 3

修复你的程序中的错误。例如,

package main

import "fmt"
import "time"

func main() {
    loc, _ := time.LoadLocation("America/Los_Angeles")
    t := time.Date(2015, 04, 12, 19, 23, 0, 0, loc)
    t2 := time.Date(2015, 03, 1, 19, 23, 0, 0, loc)
    _, offset := t.Zone()
    _, offset2 := t2.Zone()
    fmt.Printf("t1: %v  offset: %d\n", t, offset)
    fmt.Printf("t2: %v  offset: %d\n", t2, offset2)
}

输出:

t1: 2015-04-12 19:23:00 -0700 PDT  offset: -25200
t2: 2015-03-01 19:23:00 -0800 PST  offset: -28800
英文:

Fix the bug in your program. For example,

package main

import "fmt"
import "time"

func main() {
	loc, _ := time.LoadLocation("America/Los_Angeles")
	t := time.Date(2015, 04, 12, 19, 23, 0, 0, loc)
	t2 := time.Date(2015, 03, 1, 19, 23, 0, 0, loc)
	_, offset := t.Zone()
	_, offset2 := t2.Zone()
	fmt.Printf("t1: %v  offset: %d\n", t, offset)
	fmt.Printf("t2: %v  offset: %d\n", t2, offset2)
}

Output:

t1: 2015-04-12 19:23:00 -0700 PDT  offset: -25200
t2: 2015-03-01 19:23:00 -0800 PST  offset: -28800

huangapple
  • 本文由 发表于 2015年4月13日 02:42:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/29593174.html
匿名

发表评论

匿名网友

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

确定