How to compare dates in Java

Few examples show you how to compare two dates in Java. Updated with Java 8 examples.

1. Date.compareTo()

A classic method to compare two java.util.Date in Java.

  1. Return value is 0 if both dates are equal.
  2. Return value is greater than 0 , if Date is after the date argument.
  3. Return value is less than 0, if Date is before the date argument.
TestDate.java

package com.mkyong.date;

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

public class TestDate {

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

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = sdf.parse("2009-12-31");
        Date date2 = sdf.parse("2010-01-31");

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

        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 : 2009-12-31
date2 : 2010-01-31
Date1 is before Date2

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

A more user friendly method to compare two java.util.Date

TestDate2.java

package com.mkyong.date;

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

public class TestDate2 {

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

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = sdf.parse("2009-12-31");
        Date date2 = sdf.parse("2010-01-31");

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

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

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

    }

}

Output


date1 : 2009-12-31
date2 : 2010-01-31
Date1 is before Date2

3. Calender.before(), Calender.after() and Calender.equals()

Example to compare two java.util.Calendar

TestDate3.java

package com.mkyong.date;

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

public class TestDate3 {

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

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = sdf.parse("2009-12-31");
        Date date2 = sdf.parse("2010-01-31");

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

        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(date1);
        cal2.setTime(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 : 2009-12-31
date2 : 2010-01-31
Date1 is before Date2

4. Java 8

In Java 8, you can use the new isBefore(), isAfter(), isEqual() and compareTo() to compare LocalDate, LocalTime and LocalDateTime.

Review the following example to compare two java.time.LocalDate

TestDate4.java

package com.mkyong.date;

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

public class TestDate4 {

    public static void main(String[] args) {

        DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date1 = LocalDate.of(2009, 12, 31);
        LocalDate date2 = LocalDate.of(2010, 01, 31);

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

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

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

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

        System.out.println("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 : 2009-12-31
date2 : 2010-01-31
Is...
Date1 is before Date2
CompareTo...
Date1 is before Date2

References

  1. Date CompareTo JavaDoc
  2. Calendar before after JavaDoc
  3. LocalDate JavaDoc

About the Author

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

Comments

Leave a Reply

avatar
newest oldest most voted
Joe
Guest
Joe

Thanks a lot MKYong ;)

SATYA
Guest
SATYA

Thanks…very helpful

Amirouche Zeggagh
Guest
Amirouche Zeggagh

thanks

trackback
Java Date Time Tutorials

[…] Java – How to compare dates […]

Cholly Cholly
Guest
Cholly Cholly

Thanks mkyong !

Kelly S.
Guest
Kelly S.

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

Thanks in advance!! :)

Rock
Guest
Rock

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

Tanzeem
Guest
Tanzeem

Hi,
I need to compare a certain time with the current time and display a countdown timer if the specified time is less than current time and an incremental timer if the specified time is greater than current time?

Could you kindly help me with this?I can provide more details if this is not clear.

marina
Guest
marina

well thank you for this. this is a great and simple way!

trackback
Como comparar fechas en JAVA | Compartir el conocimiento - Esteban de Ortúzar
penchal
Guest
penchal

how to read a date using getParameter() and allow any type of date
Plz give me the code for it

Sudi
Guest
Sudi

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
Guest
Andres Dominguez

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

nelson
Guest
nelson

Hi!

How to get actualSystemDate?

Regards.

Jelle
Guest
Jelle

Thank you kindly.

Diego Ramos
Guest
Diego Ramos

When the dates are equal both the System.out.println(“Date1 is after Date2”); and System.out.println(“Date1 is equal Date2”); will trigger, how to fix this please.

sudeendra
Guest
sudeendra
It is not working properly. Below please check below code. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd"); Date shedualdate = sdf.parse("2012-09-19"); Date sysdate = sdf.parse("2012-08-31"); System.out.println("shedual date is: "+sdf.format(shedualdate)); System.out.println("system date is: "+sdf.format(sysdate)); if(shedualdate.compareTo(sysdate)&gt;0){ System.out.println("shedualdate is greater than sysdate"); }else if(shedualdate.compareTo(sysdate)&lt;0){ System.out.println(&quot;shedualdate is less than sysdate&quot;); }else if(shedualdate.compareTo(sysdate)==0){ System.out.println(&quot;shedualdate is equal to sysdate&quot;); }else{ System.out.println(&quot;How to get here?&quot;); } is not working properly.
sudeendra
Guest
sudeendra

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

Christian S.
Guest
Christian S.

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.

sanket
Guest
sanket
I just tried the code for android,but don’t get any output.What I am doing is the same.just had to put the date.parse() part in try catch loop apart from that no change and I checked for the equality on click of a button.. but nothing is happening with the code.I put log.i() statements for debugging but again in vain. I guess its not parsing the date.can you help me with it. I am posting my code so if you can help me I would be grateful to you c = Calendar.getInstance(); creationyear= c.get(Calendar.YEAR); creationmonth= c.get(Calendar.MONTH); creationday= c.get(Calendar.DAY_OF_MONTH); cdate=Integer.toString(creationyear)+”-“+Integer.toString(creationmonth+5)+”-“+Integer.toString(creationday); ndate=Integer.toString(creationyear+1)+”-“+Integer.toString(creationmonth+6)+”-“+Integer.toString(creationday+3); SimpleDateFormat… Read more »
manju
Guest
manju

i like this code …….great job

Nitin Lahure
Guest
Nitin Lahure

Great job…

Levan
Guest
Levan

Just what I wanted )
Thanks!

Tushar
Guest
Tushar

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.

Zamshed Farhan
Guest
Zamshed Farhan

Nice. So helpful.

NaRan
Guest
NaRan

how to get here :D lol

Priyanka Kapoor
Guest
Priyanka Kapoor

Really helpful… Keep writing..:-)