6

I want to compare two dates and check if the date has expired or not.

Here is the code I used :

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:ss:ii");
Date date1 = sdf.parse("20012-10-4 10:15:25");
Date date2 = sdf.parse("2013-10-4 10:15:25");

if(date1.equals(date12)){
    System.out.println("Both are equals");
}

I want to check the two dates but without success.

I also tried to check it like that :

if(date1 >= date2){
    System.out.println("Both are not equals");
}

But it's not working either.

rdurand
  • 7,342
  • 3
  • 39
  • 72
  • 1
    Have you read the javadoc? http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#compareTo%28java.util.Date%29 – JB Nizet Apr 10 '13 at 12:16
  • yyyy-MM-dd hh:ss:ii is not valid. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html – NickJ Apr 10 '13 at 12:17
  • [REFERENCE](http://www.mkyong.com/java/how-to-compare-dates-in-java/) – thar45 Apr 10 '13 at 12:22

6 Answers6

50

java.util.Date class has before and after method to compare dates.

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

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

if(date1.after(date2)){
    //Do Something else
}
JackPoint
  • 4,031
  • 1
  • 30
  • 42
prashant
  • 1,805
  • 12
  • 19
5

Try using this Function.It Will help You:-

public class Main {   
public static void main(String args[]) 
 {        
  Date today=new Date();                     
  Date myDate=new Date(today.getYear(),today.getMonth()-1,today.getDay());
  System.out.println("My Date is"+myDate);    
  System.out.println("Today Date is"+today);
  if(today.compareTo(myDate)<0)
     System.out.println("Today Date is Lesser than my Date");
  else if(today.compareTo(myDate)>0)
     System.out.println("Today Date is Greater than my date"); 
  else
     System.out.println("Both Dates are equal");      
  }
}
tusharagrawa
  • 371
  • 2
  • 5
  • 20
3

Read JavaDocs.

Use method:

 Date.compareTo()
Nazik
  • 8,696
  • 27
  • 77
  • 123
Andremoniy
  • 34,031
  • 20
  • 135
  • 241
2

You should look at compareTo function of Date class.

JavaDoc

Himanshu Bhardwaj
  • 4,038
  • 3
  • 17
  • 36
1

You can use:

date1.before(date2);

or:

date1.after(date2);
BobTheBuilder
  • 18,858
  • 6
  • 40
  • 61
1

You equals(Object o) comparison is correct.

Yet, you should use after(Date d) and before(Date d) for date comparison.

Jean Logeart
  • 52,687
  • 11
  • 83
  • 118