Golang 如何比较时间

Golang 如何比较时间

通过使用 Before()After() 以及 Equal() 函数,我们可以比较时间和日期,但我们也将使用 time.Now()time.Now().Add() 函数进行比较。

使用的函数: 这些函数比较秒数的时间。

  • Before(temp) - 此函数用于检查给定时间是否在临时时间变量之前,并在时间变量在临时时间变量之前返回true,否则返回false。
  • After(temp) - 此函数用于检查给定时间是否在临时时间变量之后,并在时间变量在临时时间变量之后返回true,否则返回false。
  • Equal(temp) - 此函数用于检查给定时间是否等于临时时间变量,并在时间变量等于临时时间变量时返回true,否则返回false。

示例1: 在此示例中,我们可以看到通过使用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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程