isSameDay()
is a DateUtils
class that is used to check if two Date/Calendar objects are on the same day, ignoring time.
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 isSameDay(final Date date1, final Date date2)
final Date date1
: The first date.final Date date2
: The second date.This method returns true
if the dates represent the same day. Otherwise, it returns false
.
public static boolean isSameDay(final Calendar cal1, final Calendar cal2)
import org.apache.commons.lang3.time.DateUtils;import java.util.Date;public class Main{public static void main(String[] args) {// Example 1Date date1 = new Date();Date date2 = new Date();System.out.printf("DateUtils.isSameDay(%s, %s) = %s", date1, date2, DateUtils.isSameDay(date1, date2));System.out.println();// Example 2date1 = new Date();date2 = new Date(123454321);System.out.printf("DateUtils.isSameDay(%s, %s) = %s", date1, date2, DateUtils.isSameDay(date1, date2));}}
date1 = Sun Nov 21 03:52:28 IST 2021
date2 = Sun Nov 21 03:52:28 IST 2021
The method returns true
because the dates have the same day.
date1 = Sun Nov 21 03:52:28 IST 2021
date2 = Fri Jan 02 15:47:34 IST 1970
The method returns false
because the dates have different days.
The output of the code will be as follows:
DateUtils.isSameDay(Sun Nov 21 03:52:28 IST 2021, Sun Nov 21 03:52:28 IST 2021) = true
DateUtils.isSameDay(Sun Nov 21 03:52:28 IST 2021, Fri Jan 02 15:47:34 IST 1970) = false