Search code examples
javaandroiddatedate-comparison

Comparing dates in java not working as expected


I am trying to compare 2 dates 1 is passing by paramter from the user and the other one is the current date. now for the following code its working only if the interval between the 2 dates is biiger than 1. for example if i choose the date 10/12/2015 and the current date is 9/12/15 i got false but if the chosen date is 11/12/15 and current date is 9/12/15 i got true.

this is my code:

chosen_date = bundle.getString("date");
if ((new SimpleDateFormat("dd/MM/yyyy").parse(chosen_date).getTime() / (1000 * 60 * 60 * 24)) > System.currentTimeMillis() / (1000 * 60 * 60 * 24)) {
     datecompre = true;
     Log.d("date equ","date is bigger");
} else {
     datecompre = false;
     Log.d("date equ","date is smaller");
}

Solution

  • I suggest you to use Date.after() and Date.before() methods.

    This is an example:

    try{
    
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        Date date1 = sdf.parse("yourFirstDate"); //or just "new Date();" if you want the current date
        Date date2 = sdf.parse("yourSecondDate"); 
    
        if(date1.after(date2)){
           Log.d("Date1 is after Date2");
        } else if(date1.before(date2)){
           Log.d("Date1 is before Date2");
        } else {
           Log.d("Date1 is equal Date2");
        }
    
    }catch(ParseException e){
         e.printStackTrace();
    }