golang compare time size

The methods for comparing the time size in golang are: Before, After, Equal

The time types can be compared directly

t1 := time.Now()
t2 := time.Now()
// take larger time
if t2.After(t1) {
   return t2
} else {
   return t1
}

First format the current time into a string of the same format, and then use time’s Before, After, Equal comparison

time1 := "2015-03-20 08:50:29"
time2 := "2015-03-21 09:04:25"
// first format the time string to the same time type
t1, err := time.Parse("2006-01-02 15:04:05", time1)
t2, err := time.Parse("2006-01-02 15:04:05", time2)
if err == nil && t1.Before(t2) { // t1 < t2
   //processing logic
   fmt.Println("true")
}

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish