What is DateUtils.isSameDay() in Java?

Overview

isSameDay() is a staticthe methods in Java that can be called without creating an object of the class. method of the DateUtils class that is used to check if two Date/Calendar objects are on the same day, ignoring time.

How to import 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;

Syntax


public static boolean isSameDay(final Date date1, final Date date2)

Parameters

  • final Date date1: The first date.
  • final Date date2: The second date.

Return value

This method returns true if the dates represent the same day. Otherwise, it returns false.

Overloaded methods

  • public static boolean isSameDay(final Calendar cal1, final Calendar cal2)

Code

import org.apache.commons.lang3.time.DateUtils;
import java.util.Date;
public class Main{
public static void main(String[] args) {
// Example 1
Date 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 2
date1 = new Date();
date2 = new Date(123454321);
System.out.printf("DateUtils.isSameDay(%s, %s) = %s", date1, date2, DateUtils.isSameDay(date1, date2));
}
}

Example 1

  • 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.

Example 2

  • 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.

Output

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

Free Resources