Home > Mobile >  How to compare two time instants in an accurate way?
How to compare two time instants in an accurate way?

Time:01-10

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.

CodePudding user response:

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.

  •  Tags:  
  • Related