How do I compare dates in between in Java?
Example:
date1 is 22-02-2010
date2 is 07-04-2010
today
date3 is 25-12-2010
date3
is always greater than date1
and date2
is always today. How do I verify if today's date is in between date1 and date 3?
In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.
For comparing the two dates, we have used the compareTo() method. If both dates are equal it prints Both dates are equal. If date1 is greater than date2, it prints Date 1 comes after Date 2. If date1 is smaller than date2, it prints Date 1 comes after Date 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.
The after() method is used to check if a given date is after another given date. Return Value: true if and only if the instant represented by this Date object is strictly later than the instant represented by when; false otherwise.
Date has before and after methods and can be compared to each other as follows:
if(todayDate.after(historyDate) && todayDate.before(futureDate)) { // In between }
For an inclusive comparison:
if(!historyDate.after(todayDate) && !futureDate.before(todayDate)) { /* historyDate <= todayDate <= futureDate */ }
You could also give Joda-Time a go, but note that:
Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).
Back-ports are available for Java 6 and 7 as well as Android.
Use compareTo:
date1.compareTo(date2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With