Day difference comparison

I have my codes here Go Playground - The Go Programming Language. What I do is first I have my local time then I convert it to said timezone based on my local time. Then I do a comparison which I want to find out if the second date in this case based on my codes here result := dateExistFormat.Truncate(24 * time.Hour).Compare(dateNewFormat.Truncate(24 * time.Hour)). If the dateNewFormat has cross the day meaning it a new day already. But this comparison show still as 0. What is the right method to compare to know if the day itself are different ? Also I would like to find out how may day are those dates based only on the day value without taking the time.

Truncate operates on the time as an absolute duration since the zero time; it does not operate on the presentation form of the time.

Hi Mje,
Yes I am using this package. I dont quite get you on this" Truncate operates on the time as an absolute duration since the zero time; it does not operate on the presentation form of the time." ?

time.Time is milliseconds since midnight Jan 1, 1970 UTC. That’s what the quotation from the documentation means by absolute duration since the zero time. Print your times as UTC to see that they are in the same day relative to the zero time.

The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC.

Hi Mje,
I found this method dateExistDay, error := time.Parse("2006-01-02", dateExistFormat.String()[0:10]). Where from the conversion I further do a parsing this round just to get the day which seems to be working though.

Doesn’t this work for you for dates in the same time zone?

func sameDay(date1,date2 time.Time) bool {
  y1, m1, d1 := date1.Date()
  y2, m2, d2 := date2.Date()
  return y1==y2 && m1==m2 && d1==d2
}

It would save format/parse roundtrips.

Hi Jeff,
Ok this seems to be ok. But let say I would like to know the difference in the number of day what you suggest ? Cause I saw there is one Sub function which works though but via that format and parse method.

time.Sub (and Add) will work. Only Truncate and Round work relative to zero time.

Hi Jeff,
Thank you for the confirmation I will do my tests soon on all this and fix the right method.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.