Compare time and date
suggest changeSometimes you need to know whether two time.Time values are the same instant, or which one is later.
Four comparisons:
date1 == date2is true when the two values are identical, including location and monotonic clockdate1 != date2is true when they are not identicaldate1.Before(date2)is true when the first instant is strictly before the seconddate1.After(date2)is true when the first instant is strictly after the second
== does not mean "the same instant" in every case. It also compares the Location and the monotonic clock reading. Use Equal to compare instants. Before and After compare instants.
WARNING: When the two times are the same instant,
AfterandBeforereturn false. A time is neither before nor after itself.date1.Equal(date1)is true,date1.After(date1)is false, anddate1.Before(date1)is false.
TIP:
!date1.Before(date2)is true whendate1is after or equal todate2.!date1.After(date2)is true whendate1is before or equal todate2.
Some examples to see how to use:
// Init 2 dates for example
var date1 = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
var date2 = time.Date(2017, time.July, 25, 16, 22, 42, 123, time.UTC)
var date3 = time.Date(2017, time.July, 25, 16, 22, 42, 123, time.UTC)
bool1 := date1.Before(date2) // true, because date1 is before date2
bool2 := date1.After(date2) // false, because date1 is not after date2
bool3 := date2.Before(date1) // false, because date2 is not before date1
bool4 := date2.After(date1) // true, because date2 is after date1
bool5 := date1 == date2 // false, not the same time
bool6 := date2 == date3 // true, different variables, the same time
bool7 := date1 != date2 // true, different times
bool8 := date2 != date3 // false, the same time
bool9 := date2.After(date3) // false, date2 is not after date3 (they are equal)
bool10 := date2.Before(date3) // false, date2 is not before date3 (they are equal)
bool11 := !date2.Before(date3) // true, because date2 is not before date3
bool12 := !date2.After(date3) // true, because date2 is not after date3
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents