Learn to compare two given dates in Java to find out which date is earlier and which is later in the universal timeline. We will see date comparison examples using the following classes:
LocalDate
,LocalDateTime
andZonedDateTime
classes from Java 8Date
andCalendar
(till Java 7)
1. Date Comparison since Java 8
1.1. Core Classes
The most used date classes in Java 8 are:
java.time.LocalDate
– Only the date , without time and timezone.java.time.LocalDateTime
– Only date and time, without timezonejava.time.ZonedDateTime
– Date and time with timezone.java.time.Instant
– seconds passed since the epoch (midnight of January 1, 1970 UTC)
1.2. How to Compare Dates
All the above classes have methods for comparing two instances of themselves i.e. isAfter()
, isBefore()
, isEqual()
and compareTo()
.
- date1.isAfter( date2 ) – It returns
true
is date1 comes after date2; elsefalse
. - date1.isBefore( date2 ) – It returns
true
is date1 comes before date2; elsefalse
. - date1.isEqual( date2 ) – It returns
true
is date1 is equal to date2; elsefalse
. - date1.compareTo( date2 ) – It returns ‘positive number’ is date1 comes after date2; else ‘negative number’. A value
'0'
means both dates are equal.
It is very important to note that :
- If we want to compare only the date part and do not care about which part of time it is – then use
LocalDate
instances. LocalDateTime
andZonedDateTime
compare time part as well, so even if the day they represent is same calendar day, if time is not same then they are not equal.- Use toLocalDate() to get the date part from
LocalDateTime
andZonedDateTime
instances.
1.3. Demo
Java program to compare two instances of the LocalDate class.
LocalDate today = LocalDate.now();
LocalDate anotherDay = LocalDate.of(2018, 01, 10);
System.out.println(today.isEqual(anotherDay)); //false
System.out.println(today.isAfter(anotherDay)); //true
System.out.println(today.isBefore(anotherDay)); //false
int diff = today.compareTo(anotherDay);
if(diff > 0) {
System.out.println(today + " is greater than " + anotherDay);
} else if (diff < 0) {
System.out.println(today + " is less than " + anotherDay);
} else {
System.out.println(today + " is equal to " + anotherDay);
}
Java program to compare to LocalDateTime instances.
LocalDateTime instance = LocalDateTime.now();
// To have different time part in both instances
Thread.currentThread().sleep(100);
LocalDateTime anotherInstance = LocalDateTime.now();
// Compare only date part
boolean isEqual = instance.toLocalDate()
.isEqual(anotherInstance.toLocalDate());
System.out.println(isEqual); //true
// Compare date and time parts
System.out.println(instance.isEqual(anotherInstance)); // false
System.out.println(instance.isAfter(anotherInstance)); // false
System.out.println(instance.isBefore(anotherInstance)); // true
Java program to compare two ZonedDateTime instances. Note that the comparison using the compareTo() is based first on the instant, then on the local date-time, then on the zone ID, then on the chronology. In other words, it compares all the date and time fields in both instances. So, if two instances present exactly the same time in the universal timeline, but they are in the different timezones then compareTo() method will not return zero.
To correctly compare the two ZonedDateTime with respect to the epoch time, compare the zdt.toInstant() field. Or we can use isBefore(), isEqual() or isAfter() methods that compare the epoch seconds.
ZonedDateTime now = ZonedDateTime.now();
//If we want to convert to the same instant in diferent timezone
ZonedDateTime nowInUTC = now.withZoneSameInstant(ZoneId.of("UTC"));
ZonedDateTime zdtInUTC = ZonedDateTime
.parse("2022-02-15T11:21:12.123+05:30[UTC]");
long difference = nowInUTC.toInstant()
.compareTo(zdtInUTC.toInstant());
if (difference > 0) {
System.out.println("zoneddatetime1 > zoneddatetime2");
} else if (difference < 0) {
System.out.println("zoneddatetime1 < zoneddatetime2");
} else {
System.out.println("\"zoneddatetime1 = zoneddatetime2");
}
2. Date Comparison till Java 7
2.1. Core Classes
The most used date classes till Java 7 were:
java.util.Date
java.util.Calendar
2.2. Comparison Methods
Both, Date
and Calendar
classes have methods before()
, after()
, equals()
and compareTo()
methods for date comparison purposes.
date1.after( date2 )
– It returnstrue
is date1 comes after date2; elsefalse
.date1.before( date2 )
– It returnstrue
is date1 comes before date2; elsefalse
.date1.equals( date2 )
– It returnstrue
is date1 and date2 are equal; elsefalse
.date1.compareTo( date2 )
– It returns ‘positive number’ is date1 comes after date2; else ‘negative number’. A value'0'
means both dates are equal.
Note: Both,
Date
andCalendar
classes have time part and above methods use it for comparing. So, if you want to compare only date part and do not care time part of it, then you need to extract day/month/year from other instances are compare them one to one.
2.3. Comparing Date Instances
In the given code, we first compare the two date instances including their time part.
Date date1 = new Date();
// To have different time part in both instances
Thread.currentThread().sleep(100);
Date date2 = new Date();
System.out.println(date1.equals(date2)); // false
System.out.println(date1.after(date2)); // false
System.out.println(date1.before(date2)); // true
Now we will compare both dates for only their date part excluding any time part associated with instances. We are using the Calendar class to extract the day, month and year information from the Date instance.
Date date1 = new Date();
Thread.currentThread().sleep(100);
Date date2 = new Date();
int diff = compareDatePartOnly(date1, date2);
if (diff > 0) {
System.out.println(date1 + " is greater than " + date2);
} else if (diff < 0) {
System.out.println(date1 + " is less than " + date2);
} else {
System.out.println(date1 + " is equal to " + date2);
}
private static int compareDatePartOnly(final Date date1, final Date date2) {
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
int result = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
if (result == 0) {
result = cal1.get(Calendar.DAY_OF_YEAR) - cal2.get(Calendar.DAY_OF_YEAR);
}
return result;
}
Happy Learning !!