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

How to Compare Dates Without the Time Portion?

Barbara Streisand
Release: 2024-11-08 07:21:01
Original
779 people have browsed it

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);
Copy after login

Alternatively, use DateTimeComparator:

return DateTimeComparator.getDateOnlyInstance().compare(first, second);
Copy after login

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);
Copy after login

Quick Reference for Android Developers

Add the Joda Time dependency:

dependencies {
  ...
  implementation 'joda-time:joda-time:2.9.9'
}
Copy after login

Code example:

DateTimeComparator dateTimeComparator = DateTimeComparator.getDateOnlyInstance();

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template