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 comparison.
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.
package main
import "fmt"
import "time"
func main() {
today := time .Now()
tomorrow := today.Add(24 * time .Hour)
g1 := today.Before(tomorrow)
fmt.Println( "today before tomorrow:" , g1)
g2 := tomorrow.After(today)
fmt.Println( "tomorrow after today:" , g2)
}
|
Output :
today before tomorrow: true
tomorrow after today: true
Example #2 :
package main
import "fmt"
import "time"
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" )
}
if today.Equal(sameday) {
fmt.Println( "today is sameday" )
}
}
|
Output :
today is not tomorrow
sameday is today
today is sameday
Last Updated :
27 Jul, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...