How to compare dates in Java

Here are three examples to compare two dates in Java.

1. Date.compareTo()

A classic method to compare two dates in Java.

– Return value is 0 if both dates are equal.
– Return value is greater than 0 , if Date is after the date argument.
– Return value is less than 0, if Date is before the date argument.

package com.mkyong.date;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class App 
{
     public static void main( String[] args ) 
    {
    	try{
 
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        	Date date1 = sdf.parse("2009-12-31");
        	Date date2 = sdf.parse("2010-01-31");
 
        	System.out.println(sdf.format(date1));
        	System.out.println(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?");
        	}
 
    	}catch(ParseException ex){
    		ex.printStackTrace();
    	}
    }
}

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

A more user friendly method to compare two dates. Java developers seldom use this method, not really sure what may causing it, may be they just didn’t aware of it?

package com.mkyong.date;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class App 
{
    public static void main( String[] args ) 
    {
    	try{
 
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        	Date date1 = sdf.parse("2009-12-31");
        	Date date2 = sdf.parse("2010-01-31");
 
        	System.out.println(sdf.format(date1));
        	System.out.println(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");
        	}
 
    	}catch(ParseException ex){
    		ex.printStackTrace();
    	}
    }
}

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

Most common way to compare two dates with Calendar object, and believe it’s most widely used method.

package com.mkyong.date;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
 
public class App 
{
     public static void main( String[] args ) 
    {
    	try{
 
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        	Date date1 = sdf.parse("2009-12-31");
        	Date date2 = sdf.parse("2010-01-31");
 
        	System.out.println(sdf.format(date1));
        	System.out.println(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");
        	}
 
    	}catch(ParseException ex){
    		ex.printStackTrace();
    	}
    }
}
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.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

  • Pingback: Como comparar fechas en JAVA | Compartir el conocimiento - Esteban de Ortúzar()

  • penchal

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

  • 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

  • http://[email protected] Andres Dominguez

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

  • nelson

    Hi!

    How to get actualSystemDate?

    Regards.

  • Jelle

    Thank you kindly.

  • 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

    It is not working properly.
    Below please check below code.

    SimpleDateFormat sdf = new SimpleDateFormat(&quot;yyyy-mm-dd&quot;);
    Date shedualdate = sdf.parse(&quot;2012-09-19&quot;);        	
            	Date sysdate = sdf.parse(&quot;2012-08-31&quot;);
     
            	System.out.println(&quot;shedual date is: &quot;+sdf.format(shedualdate));
            	System.out.println(&quot;system date is: &quot;+sdf.format(sysdate));
     
            	if(shedualdate.compareTo(sysdate)&amp;gt;0){
            		System.out.println(&quot;shedualdate is greater than sysdate&quot;);
            	}else if(shedualdate.compareTo(sysdate)&amp;lt;0){
            		System.out.println(&amp;quot;shedualdate is less than sysdate&amp;quot;);
            	}else if(shedualdate.compareTo(sysdate)==0){
            		System.out.println(&amp;quot;shedualdate is equal to sysdate&amp;quot;);
            	}else{
            		System.out.println(&amp;quot;How to get here?&amp;quot;);
            	}

    is not working properly.

  • sudeendra

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

  • http://priyankacool10.wordpress.com Priyanka Kapoor

    Really helpful… Keep writing..:-)

  • Christian S.

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

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

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

    • http://www.mkyong.com mkyong

      Christian, you made a good point here. Thanks for sharing.

  • 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 sdf=new SimpleDateFormat(“yyyy-MM-dd”);

    try
    {
    date1=sdf.parse(cdate);
    Log.i(“date1″,”date1″);
    }
    catch (ParseException e)
    {
    e.printStackTrace();
    }

    and next piece of code is written on button click

    if(date1.compareTo(date2)>0){
    Log.i(“Result”, “Date1 is after Date2″);
    }
    else if(date1.compareTo(date2)<0)
    {
    Log.i("Result","Date1 is before Date2");
    }
    else if(date1.compareTo(date2)==0)
    {
    Log.i("Result","Date1 is equal to Date2");
    }
    else
    {
    Log.i("Result","How to get here?");
    }

    • manju

      i like this code …….great job

  • Nitin Lahure

    Great job…

  • Levan

    Just what I wanted )
    Thanks!

    • 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.

  • http://www.zamshed.info Zamshed Farhan

    Nice. So helpful.