如何准确地比较两个时间点?

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

How to compare two time instants in an accurate way?

问题

我有两个时间实例。have 是我从数据库中获取的时间,Now() 是当前时间。当我使用 After 来比较它们时,结果并不是我期望的那样。这两个实例如下所示:

// have => 2022-01-09 09:09:59 +0000 +0000
// now  => 2022-01-09 11:57:08.990265878 +0300 +0300 m=+4.977355713
 
if now.After(have) {
    // ...
}

我期望上述条件返回 true,但实际上返回的是 false。为了更好地理解问题,我使用 Unix() 将它们转换为 Unix 时间,令人惊讶的是,have 的值稍微大于 now,这就是条件返回 false 的原因。

显然,nowhave 之后,但它的 Unix 时间却小于 have
由于我对这个情况感到困惑,你能告诉我我错在哪里吗?

更新
问题出在时区上。
我没有注意到这一点。所以我添加了以下代码:

loc, _ := time.LoadLocation("Local")
have = have.In(loc)

然后,一旦我打印出来,它就是这样的:

have => 2022-01-09 12:09:59 +0300 +0300

这就是条件返回 false 的原因。

英文:

I have two time instances. have which I fetch from a database and Now() time. Once I want to compare them using After, the result is not the one which I expected. The instances are as follow:

// have => 2022-01-09 09:09:59 +0000 +0000
// now  => 2022-01-09 11:57:08.990265878 +0300 +0300 m=+4.977355713
 
if now.After(have) {
    // ...
}

I expected the true result from the above condition, while it returns false. To figure it out better, I converted them to Unix time with Unix() and surprisingly the value of have was slightly greater than now and that is why the condition returns false.

Obviously now is after have but its Unix time is less than have.
As I am wondering regarding the case, would you please let me know where am I wrong?

Update
The problem was about time zones.
I have not noticed about it. So I added the following code:

loc, _ := time.LoadLocation("Local")
	have = have.In(loc)

and then once I printed it out, it was like this:

have => 2022-01-09 12:09:59 +0300 +0300

That is why the condition was returning false.

答案1

得分: 1

两个时间处于不同的时区:have 是在 UTC 时区,而 now 是在 +0300 时区。因此,在将 now 的日期/时间部分与另一个时间进行比较之前,你需要从 now 的值中减去 3 小时。

英文:

The two times are in different timezones: have is in UTC, and now is in +0300. Thus you have to subtract 3 hours from the date/time part of the now value before comparing it to the other time.

huangapple
  • 本文由 发表于 2022年1月9日 17:15:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/70639858.html
匿名

发表评论

匿名网友

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

确定