Before()After()Equal()time.Now()time.Now().Add()

使用的函数:这些函数将时间作为进行比较。

Before(temp)After(temp)Equal(temp)
Before()After()
// Golang program to compare times
package main
  
import "fmt"
  
// importing time module
import "time"
  
// Main function
func main() {
  
    today := time.Now()
    tomorrow := today.Add(24 * time.Hour)
  
    // Using time.Before() method
    g1 := today.Before(tomorrow)
    fmt.Println("today before tomorrow:", g1)
  
    // Using time.After() method
    g2 := tomorrow.After(today)
    fmt.Println("tomorrow after today:", g2)
  
}

输出 :

today before tomorrow: true
tomorrow after today: true

示例#2:

// Golang program to compare times
package main
  
import "fmt"
  
// importing time module
import "time"
  
// Main function
func main() {
  
    today := time.Now()
    tomorrow := today.Add(24 * time.Hour)
    sameday := tomorrow.Add(-24 * time.Hour)
  
    if today != tomorrow {
        fmt.Println("today is not tomorrow")
    }
  
    if sameday == today {
        fmt.Println("sameday is today")
    }
  
    // using Equal function
    if today.Equal(sameday) {
        fmt.Println("today is sameday")
    }
  
}

输出 :

today is not tomorrow
sameday is today
today is sameday