去时间比较 [英] Go time comparison

查看:57
本文介绍了去时间比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建简单的功能,只是将一个时间的时区更改为另一个时区(假设UTC为+0700 WIB).此处是源代码.我有2个函数,第一个 GenerateWIB 可以将您的时区更改为具有相同日期时间的+0700 WIB.第二个是 GenerateUTC ,它将给定时间的时区更改为 UTC . GenerateUTC 可以完美地工作,而另一个则不能.

I'm trying to create simple function just to change time zone of a time to another (Lets assume UTC to +0700 WIB). Here is the source code. I have 2 functions, first GenerateWIB which will change just your time zone into +0700 WIB with same datetime. Second is GenerateUTC which will change given time's timezone into UTC. GenerateUTC works perfectly while another is not.

expect := time.Date(2016, 12, 12, 1, 2, 3, 4, wib)
t1 := time.Date(2016, 12, 12, 1, 2, 3, 4, time.UTC)
res := GenerateWIB(t1)
if res != expect {
    fmt.Printf("WIB Expect %+v, but get %+v", expect, res)
}

res!=期望始终充满此结果.

WIB Expect 2016-12-12 01:02:03.000000004 +0700 WIB, but get 2016-12-12 01:02:03.000000004 +0700 WIB

但这是同一时间吗?我错过了什么吗?

But it is the same time right? Did i miss something?

推荐答案

有一个 .Equal() 方法来比较日期:

There is an .Equal() method to compare dates :

if !res.Equal(expect) {
   ...


引用文档:

请注意,Go ==运算符不仅会比较即时时间,还会比较位置"和单调时钟读数.因此,在不首先确保已为所有值设置相同的位置"的情况下,不应将时间"值用作地图或数据库键,这可以通过使用UTC或本地"方法来实现,并且单调时钟读数已被设置t = t.Round(0).通常,最好使用t.Equal(u)而不是t == u,因为t.Equal使用最精确的比较,并且仅当其参数之一具有单调时钟读数时才能正确处理这种情况.

Note that the Go == operator compares not just the time instant but also the Location and the monotonic clock reading. Therefore, Time values should not be used as map or database keys without first guaranteeing that the identical Location has been set for all values, which can be achieved through use of the UTC or Local method, and that the monotonic clock reading has been stripped by setting t = t.Round(0). In general, prefer t.Equal(u) to t == u, since t.Equal uses the most accurate comparison available and correctly handles the case when only one of its arguments has a monotonic clock reading.

如果您查看 time.Time (*)结构,您可以看到该结构具有三个私有字段:

If you look at the code for the time.Time(*) struct, you can see that this struct has three private fields :

type Time struct {
    ...
    wall uint64
    ext  int64

    ...
    loc *Location
}

和关于这些字段的注释清楚地表明,根据 Time 结构的构建方式,两个描述相同时间点的 Time 可能具有不同的值字段.

and the comments about those fields clearly indicate that, depending on how the Time struct was built, two Time describing the same point in time may have different values for these fields.

运行 res == Expect 比较这些内部字段的值,
运行 res.Equal(expect)会尝试做您期望的事情.

Running res == expect compares the values of these inner fields,
running res.Equal(expect) tries to do the thing you expect.

(*) time/time.go 源代码

这篇关于去时间比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆