为了账号安全,请及时绑定邮箱和手机立即绑定

使用两个不同位置对象的相同时间的时间比较失败?

使用两个不同位置对象的相同时间的时间比较失败?

Go
千万里不及你 2022-12-19 20:04:25
我希望time.Now().In(location)对象在同一时刻比较为相同,即使location对象不同,只要location对象是使用相同的name字符串创建的。为什么这种期望不成立?package mainimport (    "fmt"    "time"    "log")func main() {    const USPacificTimeZone = "US/Pacific"    location, err := time.LoadLocation(USPacificTimeZone)    if err != nil {        log.Fatal(fmt.Sprintf("Couldn't load timezone: %v", err))    }    // Exactly the same as location above, just a new instance    location2, err := time.LoadLocation(USPacificTimeZone)    if err != nil {        log.Fatal(fmt.Sprintf("Couldn't load timezone: %v", err))    }    now := time.Now()    fmt.Printf("Times using same location object: %v\n",        now.In(location) == now.In(location))    // prints:  Times using same location object: true    // Using (the identical) location2 causes the times to be different???    fmt.Printf("Times using different location objects: %v\n",        now.In(location) == now.In(location2))    // prints:  Times using different location objects: false}
查看完整描述

1 回答

?
阿晨1998

TA贡献2037条经验 获得超6个赞

使用Equal方法比较时间点:

fmt.Printf("Times using different location objects: %v\n",
    now.In(location).Equal(now.In(location2)))   // prints true

Time 类型文档描述了将 Time 值与 进行比较的陷阱 ==

请注意,Go == 运算符不仅比较时间瞬间,还会比较位置和单调时钟读数。因此,如果没有首先保证为所有值设置了相同的位置,时间值不应用作地图或数据库键,这可以通过使用 UTC 或本地方法来实现,并且单调时钟读数已被剥离设置 t = t.Round(0)。一般来说,更喜欢 t.Equal(u) 而不是 t == u,因为 t.Equal 使用可用的最准确的比较,并正确处理只有一个参数具有单调时钟读数的情况。


查看完整回答
反对 回复 2022-12-19
  • 1 回答
  • 0 关注
  • 66 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信