Golang中比较时间的方法有:Before、 After、 Equal, 但是都需要转成time类型来比较。
时间是否相等
timeStr1 := "2023-01-18 08:50:29"
timeStr2 := "2023-01-18 08:50:29"
time1, err := time.Parse("2006-01-02 15:04:05", timeStr1)
time2, err := time.Parse("2006-01-02 15:04:05", timeStr2)
if err == nil && time1.Equal(time2) {
fmt.Println("相等")
}
时间A小于时间B
timeStra := "2023-01-16 08:50:29"
timeStrb := "2023-01-17 08:50:29"
timea, err := time.Parse("2006-01-02 15:04:05", timeStra)
timeb, err := time.Parse("2006-01-02 15:04:05", timeStrb)
if err == nil && timea.Before(timeb) {
fmt.Println("小于")
}
时间A大于时间B
timeStra := "2023-01-16 08:50:29"
timeStrb := "2023-01-15 08:50:29"
timea, err := time.Parse("2006-01-02 15:04:05", timeStra)
timeb, err := time.Parse("2006-01-02 15:04:05", timeStrb)
if err == nil && timea.After(timeb) {
fmt.Println("大于")
}