.equals()
The equals()
method in the Java Calendar
class is used to determine if two calendar objects are equal. It compares the time values of the two calendar instances to check if they represent the same point in time.
Syntax
result = myCalendar.equals(obj)
The equals()
method has one parameter, obj
, and returns a boolean value. It is used to compare the time values of the calling calendar instance and the provided object. The comparison is based on the underlying time values, regardless of any additional calendar fields or time zone settings.
If the time values of both calendar instances are equal, the method returns true
, indicating that they represent the same point in time. Conversely, if the time values are not equal, the method returns false
.
Note: This comparison solely considers the time values and does not take into account other calendar fields or time zone differences.
Example
In this example, the equals()
method is used to compare two Calendar
instances, cal1
and cal2
. The time values of both instances are set to the same point in time using the cal2.setTimeInMillis(cal1.getTimeInMillis())
method.
import java.util.Calendar;public class CalendarEqualsExample {public static void main(String[] args) {// Create two Calendar instancesCalendar cal1 = Calendar.getInstance();Calendar cal2 = Calendar.getInstance();// Set the time of cal2 to be the same as cal1cal2.setTimeInMillis(cal1.getTimeInMillis());// Check if cal1 and cal2 represent the same point in timeboolean areEqual = cal1.equals(cal2);System.out.println("Are cal1 and cal2 equal? " + areEqual);}}
This results in the following output:
Are cal1 and cal2 equal? true
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly16 hours