How to compare times in Golang?

With the help of Before() and After() and Equal(), function we can compare the time as well as date but we are also going to use the time.Now() and time.Now().Add() function for comparision.

Functions Used: These functions compares the times as seconds.

  • Before(temp) – This function is used to check if the given time is before the temporary time variable and return true if the time variable comes before the temporary time variable else false.
  • After(temp) – This function is used to check if given time is after the temporary time variable and return true if time variable comes after temporary time variable else false.
  • Equal(temp) – This function is used to check if given time is equal the temporary time variable and return true if time variable equals temporary time variable else false.

Example #1 : In this example we can see that by using Before() and After() function, we are able to compare the dates by using these functions.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
  
}

chevron_right


Output :

today before tomorrow: true
tomorrow after today: true

Example #2 :

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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")
    }
  
}

chevron_right


Output :

today is not tomorrow
sameday is today
today is sameday



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.