Java Compare Two Dates

I want to compare two dates and check if the deadline 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 two dates, but to no avail.

I also tried checking it like this:

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

But it doesn’t work either.

+5
source share
6 answers
Class

java.util.Date has a before and after date comparison method.

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

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

if(date1.after(date2)){
    //Do Something else
}
+46
source

Try using this feature. He 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");      
  }
}
+4
source

JavaDocs.

:

 Date.compareTo()
+2

compareTo Date.

JavaDoc

+2

:

date1.before(date2);

date1.after(date2);
+1

equals (Object o) .

However, you should use after (date d) and earlier (date d) to compare the date.

+1
source

All Articles