Learn about How to compare two dates in Golang in the below code example. Also refer the comments in the code snippet to get a detailed view about what’s actually happening.
Contents
How to compare two dates in Golang
// Golang program to compare two dates
package main
import "fmt"
import "time"
func main() {
date1 := time.Date(2021, 3, 20, 10, 5, 20, 0, time.UTC)
date2 := time.Date(2021, 3, 20, 10, 5, 20, 0, time.UTC)
date3 := time.Date(2020, 3, 20, 10, 5, 20, 0, time.UTC)
if date1 == date2 {
fmt.Println("date1 is equal to date2")
} else {
fmt.Println("date1 is not equal to date2")
}
if date1 == date3 {
fmt.Println("date1 is equal to date3")
} else {
fmt.Println("date1 is not equal to date3")
}
}
In the above program, we imported the fmt package, which contains the files of the fmt package, and then we can use a function related to the fmt package. Here, we created three objects of time structure date1, date2, date3 initialized using Date() function. After that, we used the “==” operator to compare dates
Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.
Similar Codes :
How to print tomorrow’s date in Golang
How to print yesterday date in Golang