Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare dates in Java? [duplicate]

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?

like image 496
ant Avatar asked Apr 07 '10 12:04

ant


People also ask

How can I compare two dates in Java?

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.

How can I compare two dates?

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.

How do you check if two dates are on the same day Java?

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.

How do you check if a date is after another date in Java?

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.


2 Answers

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.

like image 76
Bart Kiers Avatar answered Oct 04 '22 12:10

Bart Kiers


Use compareTo:

date1.compareTo(date2);

like image 32
Chandra Sekar Avatar answered Oct 04 '22 10:10

Chandra Sekar