Main Tutorials

How to compare dates in Java

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 compareTo, before(), 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.mkyong.app;

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

public class CompareDate1 {

    public static void main(String[] args) 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

Terminal

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

Change the date1 to 2020-01-31.

Output

Terminal

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

Change the date1 to 2020-02-01.

Output

Terminal

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.mkyong.app;

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

public class CompareDate2 {

  public static void main(String[] args) 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

Terminal

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.mkyong.app;

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.mkyong.app;

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

public class DateWithinRange {

  public static void main(String[] args) 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

Terminal

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

Terminal

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 compareTo, before(), after() and equals() to compare two calender.

CompareCalendar.java

package com.mkyong.app;

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

public class CompareCalendar {

  public static void main(String[] args) 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

Terminal

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 compareTo, isBefore(), 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.mkyong.app;

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

public class CompareLocalDate {

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

        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

Terminal

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

Terminal

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.mkyong.app;

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

public class CompareLocalDateTime {

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

      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

Terminal

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.mkyong.app;

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

public class CompareInstant {

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

        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

Terminal

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 isBefore, isAfter 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.

DateRangeValidator.java

package com.mkyong.app;

import java.time.LocalDate;

public class DateRangeValidator {

  private final LocalDate startDate;
  private final LocalDate endDate;

  public DateRangeValidator(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.mkyong.app;

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

public class LocalDateWithinRange {

  public static void main(String[] args) 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);

      DateRangeValidator checker = new DateRangeValidator(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

Terminal

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 LocalDateTime, ZonedDateTime, 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.mkyong.app;

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

public class PlusMonthExample {

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

      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

Terminal

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

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
17 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Joe
6 years ago

Thanks a lot MKYong 😉

Kelly S.
9 years ago

Hello!
I want to know if the time (a) is greater than time (b) by 6 months.
Please advise!

Thanks in advance!! 🙂

Rock
9 years ago

Thanks MKYong….Saved me lot of time and gained lot of knowledge

Christian S.
11 years ago

I would like to point out that if you compare with equals two date with different format:

     SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd H:m:s");
     SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
      
     Date date1 = sdf1.parse("2012-07-26 00:00:01");
     Date date2 = sdf2.parse("2012-07-26");


 the method will return false (of course). That is why more often you can see that Java developer uses Calendar instead.

Last edited 3 years ago by mkyong
Zamshed Farhan
12 years ago

Nice. So helpful.

shar
4 years ago

Hello, Thanks for the code and detailed examples. Could you pls let me know how do I compare 2 month in the format “Month yyyy” ex: “March 2019” & “April 2019”. I have to compare these dates and verify the error message and also the verify the results.

Sudi
10 years ago

Interesting post. But isn’t it better to use JodaTime library instead with the DateTimeComparator.getDateOnlyInstance and compare the two dates?

e.g. (pseudocode) below:

—————————————-

DateTime date1 = new DateTime(lhsdate);
DateTime date2 = new DateTime(rhsdate);

DateTimeComparator comparator = DateTimeComparator.getDateOnlyInstance();
System.out.println(comparator.compare(date1, date2));

—————————————-
API below:
http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTimeComparator.html

Agreed there are zillion options for solving a problem, but jodatime makes life easy for developers IMHO.

thanks!
Sudi

Andres Dominguez
10 years ago

Thank you MkYoung, very nice code and simple…..

nelson
10 years ago

Hi!

How to get actualSystemDate?

Regards.

Jelle
11 years ago

Thank you kindly.

sudeendra
11 years ago

Thanks guys, it helped me a lot in my project development.

Priyanka Kapoor
11 years ago

Really helpful… Keep writing..:-)

Srinu
5 years ago

Thnq

Levan
11 years ago

Just what I wanted )
Thanks!

Tushar
11 years ago
Reply to  Levan

good example but little bit complected this example also consider time when comparing two date objects. Need to use dateformat , so it will help to remove time part.