Home  >  Article  >  Java  >  How to Compare Dates Without the Time Portion?

How to Compare Dates Without the Time Portion?

Barbara Streisand
Barbara StreisandOriginal
2024-11-08 07:21:01670browse

How to Compare Dates Without the Time Portion?

Comparing Dates Without the Time Portion

When comparing dates, it can be necessary to ignore the time portion to focus solely on the day, month, and year. This is commonly done in scenarios such as determining if two events occur on the same day. Here's how to implement a date comparison without the time:

Using Joda Time

Joda Time provides a convenient solution for date manipulation and comparison. To compare dates without the time:

DateTime first = ...;
DateTime second = ...;

LocalDate firstDate = first.toLocalDate();
LocalDate secondDate = second.toLocalDate();

return firstDate.compareTo(secondDate);

Alternatively, use DateTimeComparator:

return DateTimeComparator.getDateOnlyInstance().compare(first, second);

Using Java built-in API (Calendar)

If Joda Time is unavailable, use the Java built-in Calendar API:

Calendar firstDate = Calendar.getInstance();
Calendar secondDate = Calendar.getInstance();

firstDate.setTime(first);
secondDate.setTime(second);

firstDate.set(Calendar.HOUR_OF_DAY, 0);
firstDate.set(Calendar.MINUTE, 0);
firstDate.set(Calendar.SECOND, 0);
firstDate.set(Calendar.MILLISECOND, 0);

secondDate.set(Calendar.HOUR_OF_DAY, 0);
secondDate.set(Calendar.MINUTE, 0);
secondDate.set(Calendar.SECOND, 0);
secondDate.set(Calendar.MILLISECOND, 0);

return firstDate.compareTo(secondDate);

Quick Reference for Android Developers

Add the Joda Time dependency:

dependencies {
  ...
  implementation 'joda-time:joda-time:2.9.9'
}

Code example:

DateTimeComparator dateTimeComparator = DateTimeComparator.getDateOnlyInstance();

Date myDateOne = ...;
Date myDateTwo = ...;

int retVal = dateTimeComparator.compare(myDateOne, myDateTwo);

The above is the detailed content of How to Compare Dates Without the Time Portion?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn