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

Date date1 = new Date();
Date date2 = new Date();

if(date1.before(date2)){
    //Do Something
}

if(date1.after(date2)){
    //Do Something else
}
Example:

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?");
        	}
Example :2

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");
        	}

http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#compareTo%28java.util.Date%29

		
Advertisements