×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang program to check two dates are equal or not

Here, we are going to learn how to check whether two given dates are equal or not in Golang (Go Language)?
Submitted by Nidhi, on March 22, 2021 [Last updated : March 04, 2023]

Checking two dates are equal or not in Golang

Problem Solution:

In this program, we will create three-date objects using the Date() function. Then we will check the equality of objects using the Equal() function and print the appropriate message on the console screen.

Program/Source Code:

The source code to check whether two given dates are equal or not is given below. The given program is compiled and executed successfully.

Golang code to check two dates are equal or not

// Golang program to check whether
// two given dates are equal or not

package main

import "fmt"
import "time"

func main() {
	date1 := time.Date(2020, 2, 5, 10, 5, 20, 0, time.UTC)
	date2 := time.Date(2020, 2, 5, 10, 5, 20, 0, time.UTC)
	date3 := time.Date(2020, 2, 7, 10, 5, 20, 0, time.UTC)

	if date1.Equal(date2) == true {
		fmt.Println("date1 and date2 are equal")
	} else {
		fmt.Println("date1 and date2 are not equal")
	}

	if date1.Equal(date3) == true {
		fmt.Println("date1 and date3 are equal")
	} else {
		fmt.Println("date1 and date3 are not equal")
	}
}

Output:

date1 and date2 are equal
date1 and date3 are not equal

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt and time packages to use time and fmt related functions.

In the main() function, we created three date-time object using Date() function. Then we compare date-time objects using Equal() function. The Equal() function returns Boolean value. If date objects are equal then Equal() function returns true otherwise it returns false.

Golang Date & Time Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.