英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论