Calendar.equals() Method in Java
Last Updated :
06 May, 2025
In Java, the Calendar.equals() is a method in the Calendar class of java.util package. This method compares the invoking Calendar object with another object. It returns true if both calendars represent the same time and have the same settings, otherwise, it returns false.
Syntax of Calendar.equals() Method
public boolean equals(Object obj)
- Parameter: obj: The object to compare with the current calendar.
- Returns: It returns true, if both calendars are equal, otherwise, it returns false.
Important Points:
- This method does not compare references only, it also compares the actual date and time data inside the calendars.
- This is useful for checking if two dates match exactly.
Examples of Calendar.equals() Method
Example 1: Comparing Two Identical Calendar References
Java
// Java program to demonstrate Calendar.equals()
// with same references
import java.util.*;
class Geeks {
public static void main(String[] args) {
// Creating a Calendar object
Calendar c1 = Calendar.getInstance();
// Assigning the same reference to another variable
Calendar c2 = c1;
System.out.println("Time 1: " + c1.getTime());
System.out.println("Time 2: " + c2.getTime());
// Comparing the calendars using equals()
System.out.println(c1.equals(c2));
}
}
OutputTime 1: Tue May 06 07:37:55 UTC 2025
Time 2: Tue May 06 07:37:55 UTC 2025
true
Explanation: In this example, both the variables refer to the same Calendar object, so they are equal. The equals() method returns true because there is no difference between the references.
Example 2: Comparing Two Different Calendar Objects
Java
// Java program to demonstrate Calendar.equals()
// with different calendar values
import java.util.*;
class Geeks {
public static void main(String[] args) {
// Creating two separate Calendar objects
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
// Printing the current date for c1
System.out.println("Current date is: " + c1.getTime());
// Changing the year of c2 to 2010
c2.set(Calendar.YEAR, 2025);
// Printing the modified year
System.out.println("Year is " + c2.get(Calendar.YEAR));
// Comparing the two calendars
System.out.println("Result: " + c1.equals(c2));
}
}
OutputCurrent date is: Tue May 06 09:12:54 UTC 2025
Year is 2025
Result: false
Explanation: In this example, the second calendar's year is modified to 2010 and made both calendars different. The equals() method returns false due to the year mismatch.
Similar Reads
Interview Preparation
Practice @Geeksforgeeks
Data Structures
Algorithms
Programming Languages
Web Technologies
Computer Science Subjects
Data Science & ML
Tutorial Library
GATE CS