GregorianCalendar equals() Method in Java
Last Updated :
29 Sep, 2021
The java.util.GregorianCalendar.equals() method is an in-built function in Java which checks for equality between this GregorianCalendar instance and the Object passed as parameter to the function. It returns true only if the specified Object is a GregorianCalendar object with same time value (millisecond offset from the Epoch) as this GregorianCalendar instance.
Syntax:
public boolean equals(Object obj)
Parameters: The function accepts a single mandatory parameter obj which is to be compared with this GregorianCalendar instance.
Return Values: This method returns true only when the specified Object is a GregorianCalendar object and has the same time value (millisecond offset from the Epoch) as this instance and returns false otherwise.
Examples:
Input : c1 = Mon Jul 23 23:46:14 UTC 2018, c2 = Mon Jul 23 23:46:14 UTC 2018
Output : true
Input : c1 = Mon Jul 23 23:46:14 UTC 2018, c2 = Sun Jul 24 00:02:52 UTC 2022
Output : false
Below programs illustrate the java.util.GregorianCalendar.equals() function:
Program 1:
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
GregorianCalendar c1 = (GregorianCalendar)
GregorianCalendar.getInstance();
System.out.println( "Current Date and Time : "
+ c1.getTime());
GregorianCalendar c2 =
(GregorianCalendar)(Calendar)c1.clone();
System.out.println( "Both calendars are equal:"
+ c1.equals(c2));
c2.add(GregorianCalendar.MONTH, 15 );
System.out.println( "Modified Date and Time : "
+ c2.getTime());
System.out.println( "Both calendars are equal:"
+ c1.equals(c2));
}
}
|
Output:
Current Date and Time : Fri Jul 27 12:05:05 UTC 2018
Both calendars are equal:true
Modified Date and Time : Sun Oct 27 12:05:05 UTC 2019
Both calendars are equal:false
Program 2:
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
GregorianCalendar c1 = (GregorianCalendar)
GregorianCalendar.getInstance();
System.out.println( "Current Date and Time : "
+ c1.getTime());
GregorianCalendar c2 =
(GregorianCalendar)(Calendar)c1.clone();
System.out.println( "Both calendars are equal:"
+ c1.equals(c2));
c2.setTimeZone(TimeZone.getTimeZone( "CST" ));
System.out.println( "Both calendars are equal:"
+ c1.equals(c2));
}
}
|
Output:
Current Date and Time : Fri Jul 27 12:05:08 UTC 2018
Both calendars are equal:true
Both calendars are equal:false
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html#equals()
Share your thoughts in the comments
Please Login to comment...