Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this quick tutorial, we’ll learn about several different ways to check if two java.util.Date objects have the same day.

We’ll start by considering solutions using core Java – namely, Java 8 features – before looking at a couple of pre-Java 8 alternatives.

To finish, we’ll also look at some external libraries — Apache Commons Lang, Joda-Time, and Date4J.

2. Core Java

The class Date represents a specific instant in time, with millisecond precision. To find out if two Date objects contain the same day, we need to check if the Year-Month-Day is the same for both objects and discard the time aspect.

2.1. Using LocalDate

With the new Date-Time API of Java 8, we can use the LocalDate object. This is an immutable object representing a date without a time.

Let’s see how we can check if two Date objects have the same day using this class:

public static boolean isSameDay(Date date1, Date date2) {
    LocalDate localDate1 = date1.toInstant()
      .atZone(ZoneId.systemDefault())
      .toLocalDate();
    LocalDate localDate2 = date2.toInstant()
      .atZone(ZoneId.systemDefault())
      .toLocalDate();
    return localDate1.isEqual(localDate2);
}

In this example, we’ve converted both the Date objects to LocalDate using the default timezone. Once converted, we just need to check if the LocalDate objects are equal using the isEqual method.

Consequently, using this approach, we’ll be able to determine if the two Date objects contain the same day.

2.2. Using Instant

In the example above, we used Instant as an intermediate object when converting Date objects to LocalDate objects. Instant, introduced in Java 8, represents a specific point in time.

We can directly truncate the Instant objects to the DAYS unit, which sets the time field values to zero, and then we can compare them:

public static boolean isSameDayUsingInstant(Date date1, Date date2) {
    Instant instant1 = date1.toInstant()
      .truncatedTo(ChronoUnit.DAYS);
    Instant instant2 = date2.toInstant()
      .truncatedTo(ChronoUnit.DAYS);
    return instant1.equals(instant2);
}

2.3. Using SimpleDateFormat

Since early versions of Java, we’ve been able to use the SimpleDateFormat class to convert between Date and String object representations. This class comes with support for conversion using many patterns. In our case, we will use the pattern “yyyyMMdd”.

Using this, we’ll format the Date, convert it to a String object, and then compare them using the standard equals method:

public static boolean isSameDay(Date date1, Date date2) {
    SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
    return fmt.format(date1).equals(fmt.format(date2));
}

2.4. Using Calendar

The Calendar class provides methods to get the values of different date-time units for a particular instant of time.

Firstly, we need to create a Calendar instance and set the Calendar objects’ time using each of the provided dates. Then we can query and compare the Year-Month-Day attributes individually to figure out if the Date objects have the same day:

public static boolean isSameDay(Date date1, Date date2) {
    Calendar calendar1 = Calendar.getInstance();
    calendar1.setTime(date1);
    Calendar calendar2 = Calendar.getInstance();
    calendar2.setTime(date2);
    return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR)
      && calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH)
      && calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
}

3. External Libraries

Now that we have a good understanding of how to compare Date objects using the new and old APIs offered by core Java, let’s take a look at some external libraries.

3.1. Apache Commons Lang DateUtils

The DateUtils class provides many useful utilities that make it easier to work with the legacy Calendar and Date objects.

The Apache Commons Lang artifact is available from Maven Central:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version>
</dependency>

Then we can simply use the method isSameDay from DateUtils:

DateUtils.isSameDay(date1, date2);

3.2. Joda-Time Library

An alternative to the core Java Date and Time library is Joda-Time. This widely used library serves an excellent substitute when working with Date and Time.

The artifact can be found on Maven Central:

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.12.5</version>
</dependency>

In this library, org.joda.time.LocalDate represents a date without time. Hence, we can construct the LocalDate objects from the java.util.Date objects and then compare them:

public static boolean isSameDay(Date date1, Date date2) {
    org.joda.time.LocalDate localDate1 = new org.joda.time.LocalDate(date1);
    org.joda.time.LocalDate localDate2 = new org.joda.time.LocalDate(date2);
    return localDate1.equals(localDate2);
}

3.3. Date4J Library

Date4j also provides a straightforward and simple implementation that we can use.

Likewise, it is also available from Maven Central:

<dependency>
    <groupId>com.darwinsys</groupId>
    <artifactId>hirondelle-date4j</artifactId>
    <version>1.5.1</version>
</dependency>

Using this library, we need to construct the DateTime object from a java.util.Date object. Then we can simply use the isSameDayAs method:

public static boolean isSameDay(Date date1, Date date2) {
    DateTime dateObject1 = DateTime.forInstant(date1.getTime(), TimeZone.getDefault());
    DateTime dateObject2 = DateTime.forInstant(date2.getTime(), TimeZone.getDefault());
    return dateObject1.isSameDayAs(dateObject2);
}

4. Conclusion

In this quick tutorial, we’ve explored several ways of checking if two java.util.Date objects contain the same day.

As always, the full source code of the article is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are closed on this article!