This article shows few examples to compare two dates in Java. Updated with Java 8 examples.

1. Compare two date

For the legacy java.util.Date, we can use compareTobefore()after() and equals() to compare two dates.

1.1 Date.compareTo

Below example uses Date.compareTo to compare two java.util.Date in Java.

  • Return value of 0 if the argument date is equal to the Date.
  • Return value is greater than 0 or positive if the Date is after the argument date.
  • Return value is less than 0 or negative if the Date is before the argument date.

Review the Date.compareTo method signature.

Date.java

package java.util;

public class Date
  implements java.io.Serializable, Cloneable, Comparable<Date> {

  public int compareTo(Date anotherDate) {
      long thisTime = getMillisOf(this);
      long anotherTime = getMillisOf(anotherDate);
      return (thisTime<anotherTime ? -1 : (thisTime==anotherTime ? 0 : 1));
  }

  //...
}

For example:

CompareDate1.java

package com.favtuts.time;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CompareDateExamples {
    
    public static void main(String[] args) throws ParseException {
        compareLegacyDateWithCompareTo();
    }

    static void compareLegacyDateWithCompareTo() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = sdf.parse("2020-01-30");
        Date date2 = sdf.parse("2020-01-31");

        System.out.println("date1 : " + sdf.format(date1));
        System.out.println("date2 : " + sdf.format(date2));

        int result = date1.compareTo(date2);
        System.out.println("result: " + result);

        if (result == 0) {
            System.out.println("Date1 is equal to Date2");
        } else if (result > 0) {
            System.out.println("Date1 is after Date2");
        } else if (result < 0) {
            System.out.println("Date1 is before Date2");
        } else {
            System.out.println("How to get here?");
        }
    }
}

Output

date1 : 2020-01-30
date2 : 2020-01-31
result: -1
Date1 is before Date2

Change the date1 to 2020-01-31.

Output

date1 : 2020-01-31
date2 : 2020-01-31
result: 0
Date1 is equal to Date2

Change the date1 to 2020-02-01.

Output

date1 : 2020-02-01
date2 : 2020-01-31
result: 1
Date1 is after Date2

1.2 Date.before(), Date.after() and Date.equals()

Below is a more user friendly method to compare two java.util.Date in Java.

CompareDate2.java

package com.favtuts.time;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CompareDateExamples {

    public static void main(String[] args) throws ParseException {
        compareDateWithFriendlyMethods();
    }

    static void compareDateWithFriendlyMethods() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // Date date1 = sdf.parse("2009-12-31");
        Date date1 = sdf.parse("2020-02-01");
        Date date2 = sdf.parse("2020-01-31");

        System.out.println("date1 : " + sdf.format(date1));
        System.out.println("date2 : " + sdf.format(date2));

        if (date1.equals(date2)) {
            System.out.println("Date1 is equal Date2");
        }

        if (date1.after(date2)) {
            System.out.println("Date1 is after Date2");
        }

        if (date1.before(date2)) {
            System.out.println("Date1 is before Date2");
        }
    }
}

Output

date1 : 2020-02-01
date2 : 2020-01-31
Date1 is after Date2

1.3 Check if a date is within a certain range

The below example uses getTime() to check if a date is within a certain range of two dates (inclusive of startDate and endDate).

DateRangeValidator.java

package com.favtuts.time;

import java.util.Date;

public class DateRangeValidator {
    private final Date startDate;
    private final Date endDate;

    public DateRangeValidator(Date startDate, Date endDate) {
        this.startDate = startDate;
        this.endDate = endDate;
    }

    // inclusive startDate and endDate
    // the equals ensure the inclusive of startDate and endDate,
    // if prefer exclusive, just delete the equals
    public boolean isWithinRange(Date testDate) {

        // it works, alternatives
        /*boolean result = false;
        if ((testDate.equals(startDate) || testDate.equals(endDate)) ||
                (testDate.after(startDate) && testDate.before(endDate))) {
            result = true;
        }
        return result;*/

        // compare date and time, inclusive of startDate and endDate
        // getTime() returns number of milliseconds since January 1, 1970, 00:00:00 GMT
        return testDate.getTime() >= startDate.getTime() &&
                testDate.getTime() <= endDate.getTime();
    }
}

DateWithinRange.java

package com.favtuts.time;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CompareDateExamples {

    public static void main(String[] args) throws ParseException {
        compareDateWithinRange();
    }

    static void compareDateWithinRange() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date startDate = sdf.parse("2020-01-01");
        Date endDate = sdf.parse("2020-01-31");

        System.out.println("startDate : " + sdf.format(startDate));
        System.out.println("endDate : " + sdf.format(endDate));

        DateRangeValidator checker = new DateRangeValidator(startDate, endDate);

        Date testDate = sdf.parse("2020-01-01");
        System.out.println("testDate : " + sdf.format(testDate));

        if (checker.isWithinRange(testDate)) {
            System.out.println("testDate is within the date range.");
        } else {
            System.out.println("testDate is NOT within the date range.");
        }
    }
}

Output

startDate : 2020-01-01
endDate   : 2020-01-31

testDate  : 2020-01-01
testDate is within the date range.

If we change the testDate to 2020-03-01.

Output

startDate : 2020-01-01
endDate   : 2020-01-31

testDate  : 2020-03-01
testDate is NOT within the date range.

2. Compare two calendar

For the legacy java.util.Calendar, the Calendar works the same way as java.util.Date. And The Calendar contains the similar compareTobefore()after() and equals() to compare two calender.

CompareCalendar.java

package com.favtuts.time;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class CompareDateExamples {

    public static void main(String[] args) throws ParseException {
        compareTwoCalendar();
    }

    static void compareTwoCalendar() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = sdf.parse("2020-02-01");
        Date date2 = sdf.parse("2020-01-31");
  
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(date1);
        cal2.setTime(date2);
  
        System.out.println("date1 : " + sdf.format(date1));
        System.out.println("date2 : " + sdf.format(date2));
  
        if (cal1.after(cal2)) {
            System.out.println("Date1 is after Date2");
        }
  
        if (cal1.before(cal2)) {
            System.out.println("Date1 is before Date2");
        }
  
        if (cal1.equals(cal2)) {
            System.out.println("Date1 is equal Date2");
        }
    }
}

Output

date1 : 2020-02-01
date2 : 2020-01-31
Date1 is after Date2

3. Compare two date and time (Java 8)

For the new Java 8 java.time.* classes, all contains similar compareToisBefore()isAfter() and isEqual() to compare two dates, and it works the same way.

  • java.time.LocalDate – date without time, no time-zone.
  • java.time.LocalTime – time without date, no time-zone.
  • java.time.LocalDateTime – date and time, no time-zone.
  • java.time.ZonedDateTime – date and time, with time-zone.
  • java.time.Instant – seconds passed since the Unix epoch time (midnight of January 1, 1970 UTC).

3.1 Compare two LocalDate

The below example shows how to compare two LocalDate in Java.

CompareLocalDate.java

package com.favtuts.time;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class CompareDateExamples {

    public static void main(String[] args) throws ParseException {
        compareTwoLocalDate();
    }

    static void compareTwoLocalDate() {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd");

        LocalDate date1 = LocalDate.parse("2020-02-01", dtf);
        LocalDate date2 = LocalDate.parse("2020-01-31", dtf);

        System.out.println("date1 : " + date1);
        System.out.println("date2 : " + date2);

        if (date1.isEqual(date2)) {
            System.out.println("Date1 is equal Date2");
        }

        if (date1.isBefore(date2)) {
            System.out.println("Date1 is before Date2");
        }

        if (date1.isAfter(date2)) {
            System.out.println("Date1 is after Date2");
        }

        // test compareTo
        if (date1.compareTo(date2) > 0) {
            System.out.println("Date1 is after Date2");
        } else if (date1.compareTo(date2) < 0) {
            System.out.println("Date1 is before Date2");
        } else if (date1.compareTo(date2) == 0) {
            System.out.println("Date1 is equal to Date2");
        } else {
            System.out.println("How to get here?");
        }
    }
}

Output

date1 : 2020-02-01
date2 : 2020-01-31
Date1 is after Date2
Date1 is after Date2

And we change the date1 to 2020-01-31.

Output

date1 : 2020-01-31
date2 : 2020-01-31
Date1 is equal Date2
Date1 is equal to Date2

3.2 Compare two LocalDateTime

The below example shows how to compare two LocalDateTime in Java, which works the same way.

CompareLocalDateTime.java

package com.favtuts.time;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class CompareDateExamples {

    public static void main(String[] args) throws ParseException {
        compareTwoLocalDateTime();
    }

    static void compareTwoLocalDateTime() {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");

        LocalDateTime date1 = LocalDateTime.parse("2020-01-31 11:44:43", dtf);
        LocalDateTime date2 = LocalDateTime.parse("2020-01-31 11:44:44", dtf);
  
        System.out.println("date1 : " + date1);
        System.out.println("date2 : " + date2);
  
        if (date1.isEqual(date2)) {
            System.out.println("Date1 is equal Date2");
        }
  
        if (date1.isBefore(date2)) {
            System.out.println("Date1 is before Date2");
        }
  
        if (date1.isAfter(date2)) {
            System.out.println("Date1 is after Date2");
        }
    }
}

Output

date1 : 2020-01-31T11:44:43
date2 : 2020-01-31T11:44:44
Date1 is before Date2

3.3 Compare two Instant

The new Java 8 java.time.Instant, return seconds passed since the Unix epoch time (midnight of January 1, 1970 UTC).

CompareInstant.java

package com.favtuts.time;

import java.text.ParseException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class CompareDateExamples {

    public static void main(String[] args) throws ParseException {
        compareTwoInstant();
    }

    static void compareTwoInstant() {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");

        LocalDateTime date1 = LocalDateTime.parse("2020-01-31 11:44:44", dtf);
        LocalDateTime date2 = LocalDateTime.parse("2020-01-31 11:44:44", dtf);

        // convert LocalDateTime to Instant
        Instant instant1 = date1.toInstant(ZoneOffset.UTC);
        Instant instant2 = date2.toInstant(ZoneOffset.UTC);

        // compare getEpochSecond
        if (instant1.getEpochSecond() == instant2.getEpochSecond()) {
            System.out.println("instant1 is equal instant2");
        }

        if (instant1.getEpochSecond() < instant2.getEpochSecond()) {
            System.out.println("instant1 is before instant2");
        }

        if (instant1.getEpochSecond() > instant2.getEpochSecond()) {
            System.out.println("instant1 is after instant2");
        }

        // compare with APIs
        if (instant1.equals(instant2)) {
            System.out.println("instant1 is equal instant2");
        }

        if (instant1.isBefore(instant2)) {
            System.out.println("instant1 is before instant2");
        }

        if (instant1.isAfter(instant2)) {
            System.out.println("instant1 is after instant2");
        }
    }
}

Output

instant1 : 2020-01-31T11:44:44Z
instant2 : 2020-01-31T11:44:44Z
instant1 is equal instant2
instant1 is equal instant2

4 Check if a date is within a certain range (Java 8)

We can use the simple isBeforeisAfter and isEqual to check if a date is within a certain date range; for example, the below program check if a LocalDate is within the January of 2020.

LocalDateRangeValidator.java

package com.favtuts.time;

import java.time.LocalDate;

public class LocalDateRangeValidator {
    private final LocalDate startDate;
    private final LocalDate endDate;

    public LocalDateRangeValidator(LocalDate startDate, LocalDate endDate) {
        this.startDate = startDate;
        this.endDate = endDate;
    }

    public boolean isWithinRange(LocalDate testDate) {

        // exclusive startDate and endDate
        // return testDate.isBefore(endDate) && testDate.isAfter(startDate);

        // inclusive startDate and endDate
        return (testDate.isEqual(startDate) || testDate.isEqual(endDate))
                || (testDate.isBefore(endDate) && testDate.isAfter(startDate));

    }
}

LocalDateWithinRange.java

package com.favtuts.time;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class CompareDateExamples {

    public static void main(String[] args) throws ParseException {
        compareLocalDateWithinRange();
    }

    static void compareLocalDateWithinRange() throws ParseException {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd");

        LocalDate startDate = LocalDate.parse("2020-01-01", dtf);
        LocalDate endDate = LocalDate.parse("2020-01-31", dtf);

        System.out.println("startDate : " + startDate);
        System.out.println("endDate : " + endDate);

        LocalDateRangeValidator checker = new LocalDateRangeValidator(startDate, endDate);

        LocalDate testDate = LocalDate.parse("2020-01-01", dtf);
        System.out.println("\ntestDate : " + testDate);

        if (checker.isWithinRange(testDate)) {
            System.out.println("testDate is within the date range.");
        } else {
            System.out.println("testDate is NOT within the date range.");
        }
    }
}

Output

startDate : 2020-01-01
endDate : 2020-01-31

testDate : 2020-01-01
testDate is within the date range.

We can use the same date range algorithm for other Java 8 time classes like LocalDateTimeZonedDateTime, and Instant.

  public boolean isWithinRange(LocalDateTime testDate) {

      // exclusive startDate and endDate
      //return testDate.isBefore(endDate) && testDate.isAfter(startDate);

      // inclusive startDate and endDate
      return (testDate.isEqual(startDate) || testDate.isEqual(endDate))
              || (testDate.isBefore(endDate) && testDate.isAfter(startDate));

  }

5 Check if the date is older than 6 months

The below shows an example to check if a date is older than 6 months.

PlusMonthExample.java

package com.favtuts.time;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class CompareDateExamples {

    public static void main(String[] args) throws ParseException {
        checkLocalDateOlderThan6Months();
    }

    static void checkLocalDateOlderThan6Months() {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd");

        LocalDate now = LocalDate.parse("2020-01-01", dtf);
        LocalDate date1 = LocalDate.parse("2020-07-01", dtf);

        System.out.println("now: " + now);
        System.out.println("date1: " + date1);

        // add 6 months
        LocalDate nowPlus6Months = now.plusMonths(6);
        System.out.println("nowPlus6Months: " + nowPlus6Months);

        System.out.println("If date1 older than 6 months?");

        // if want to exclude the 2020-07-01, remove the isEqual
        if (date1.isAfter(nowPlus6Months) || date1.isEqual(nowPlus6Months)) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
}

Output

now: 2020-01-01
date1: 2020-07-01
nowPlus6Months: 2020-07-01
If date1 older than 6 months?
Yes

Note

More examples to compare or check if a date is older than 30 days or 6 months.

Download Source Code

$ git clone https://github.com/favtuts/java-core-tutorials-examples

$ cd java-basic/time

References

Leave a Reply

Your email address will not be published. Required fields are marked *