isSameLocalTime()
is a DateUtils
class which is used to determine whether two Calendar
objects have the same local time. The method compares the different fields of both objects.
DateUtils
The definition of DateUtils
can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml
file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the commons-lang package, refer to the Maven Repository.
You can import the DateUtils
class as follows:
import org.apache.commons.lang3.time.DateUtils;
public static boolean isSameLocalTime(Calendar cal1, Calendar cal2)
Calendar cal1
: The first object to check.Calendar cal2
: The second object to check.This method returns true
if the two objects represent the same instant in milliseconds. Otherwise, it returns false
.
import org.apache.commons.lang3.time.DateUtils;import java.util.Calendar;public class Main{public static void main(String[] args) {// Example 1Calendar calendar1 = Calendar.getInstance();System.out.printf("DateUtils.isSameLocalTime(%s, %s) = %s", calendar1.getTime(), calendar1.getTime(), DateUtils.isSameLocalTime(calendar1, calendar1));System.out.println();// Example 2calendar1 = Calendar.getInstance();Calendar calendar2 = Calendar.getInstance();calendar2.add(Calendar.HOUR, 3);System.out.printf("DateUtils.isSameLocalTime(%s, %s) = %s", calendar1.getTime(), calendar2.getTime(), DateUtils.isSameLocalTime(calendar1, calendar2));System.out.println();}}
Sun Nov 21 13:08:08 IST 2021
Sun Nov 21 13:08:08 IST 2021
The method returns true
as the time part of both the calendar objects is the same.
Sun Nov 21 13:08:08 IST 2021
Sun Nov 21 16:08:08 IST 2021
In the second example, we modify the HOUR
part of the second calendar object using the add()
method of the Calendar
class.
The method returns false
as the times of the calendar objects are different.
The output of the code will be as follows:
DateUtils.isSameLocalTime(Sun Nov 21 13:08:08 IST 2021, Sun Nov 21 13:08:08 IST 2021) = true
DateUtils.isSameLocalTime(Sun Nov 21 13:08:08 IST 2021, Sun Nov 21 16:08:08 IST 2021) = false