Search code examples
androiddateequalscompareto

dont get expected result using method `compareTo()` and `equals()`


I need to compare two dates. which I read one of them from my database that its type is String. so first i convert String to Date in the specific format that i need, then I get the second Date from system again in the format that I want. my problem is even when they are same i get unexpected result.

my code is:

public class SaharDateComparerActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sahar_date_comparer);
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    String dateString ="18/02/2015";


    Date datee = convertStringToDate(dateString);
    Log.i("SAHAR","date 1:  "+ dateFormat.format(datee).toString());


    Date myDate = new Date();
    Log.i("SAHAR", "date 2:  "+dateFormat.format(myDate).toString());

    int testttt=    datee.compareTo(myDate);
    boolean a = datee.toString().equals(myDate.toString());
    Log.i("SAHAR", "date compared:  "+String.valueOf(testttt));
    Log.i("SAHAR", "date equal:  "+String.valueOf(a));

}

public Date convertStringToDate(String strDate) {
    // String startDateString = "06/27/2007";
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    Date date = null;
    try {
        date = df.parse(strDate);
        String newDateString = df.format(date);
        System.out.println(newDateString);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return date;
 }
}

and what i get is this

as you can see my two dates are same but i get -1 when i use compareTo() and false when i use equals() method!!!


Solution

  • You should compare your Date objects after clearing the time units missing in the date coming from the database i.e. without hours, minutes, seconds etc. This is what is affecting your results.

    String dateString ="18/02/2015";
    Date datee = convertStringToDate(dateString);
    
    Calendar c = Calendar.getInstance();
    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);
    
    Log.i("SAHAR", "Comparison result: " + datee.equals(c.getTime()));