Search code examples
androidandroid-datepickerandroid-date

Issue in date comparision using compareTo() method in android


I am trying to compare two dates in android in the 24 hour format following is the date formats but both are giving same result when trying one after other.

SimpleDateFormat simpleDateFormat24Hour = new SimpleDateFormat("mm/dd/yyyy HH:mm");

SimpleDateFormat simpleDateFormat24Hour = new SimpleDateFormat("mm/dd/yyyy HH:mm", Locale.US);

Log.e(startDateEditText.getText().toString().trim());
Log.e(endDateEditText.getText().toString().trim());
Date startDate = simpleDateFormat24Hour.parse(startDateEditText.getText().toString().trim());
Date endDate = simpleDateFormat24Hour.parse(endDateEditText.getText().toString().trim());
if (startDate.compareTo(endDate) > 0) {
    showAlertDialog("End date should greater than start date.");
}

following are the inputs for start and end date respectively

04/20/2017 11:07

05/18/2017 11:22

if the end date selection is one month greater or if select next month's date then this issue arises but if date selection is from same month then this works fine.

please suggest some tips to resolve this issue. Thanks in advance.


Solution

  • Try this,

    if (false == isDateAfter("04/20/2017 11:07", "05/18/2017 11:22")) {
         showAlertDialog("End date should greater than start date.");
    }
    

    isDateAfter Method:

    public static boolean isDateAfter(String startDate, String endDate) {
        try {
            String myFormatString = "dd-MM-yyyy"; // for example
            SimpleDateFormat df = new SimpleDateFormat(myFormatString, Locale.ENGLISH);
            Date endingDate = df.parse(endDate);
            Date startingDate = df.parse(startDate);
    
            return endingDate.equals(startingDate) || !endingDate.after(startingDate);
        } catch (Exception e) {
            return false;
        }
    }