登录
首页 >  Golang >  Go问答

对两个位置对象进行同时时间比较无法成功?

来源:stackoverflow

时间:2024-02-08 16:15:24 448浏览 收藏

编程并不是一个机械性的工作,而是需要有思考,有创新的工作,语法是固定的,但解决问题的思路则是依靠人的思维,这就需要我们坚持学习和更新自己的知识。今天golang学习网就整理分享《对两个位置对象进行同时时间比较无法成功?》,文章讲解的知识点主要包括,如果你对Golang方面的知识点感兴趣,就不要错过golang学习网,在这可以对大家的知识积累有所帮助,助力开发能力的提升。

问题内容

我期望 time.now().in(location) 对象在同一时刻比较为相同,即使 location 对象不同,只要 location 对象是使用相同的 name 创建的字符串。

为什么这种期望不成立?

package main

import (
    "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
}

正确答案


使用 Equal 方法来比较时间瞬间:

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

Time type documentation 描述了将时间值与 == 进行比较的陷阱:

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

本篇关于《对两个位置对象进行同时时间比较无法成功?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>