Search code examples
androiddateif-statementandroid-fragmentsandroid-datepicker

End-date greater than start-date validation - Android


I have two DatePicker. One with start date and other with end date. I need to make a validation and check if end date is greater than start-date.

I done the code like this:

DatePicker sdateInput = (DatePicker) getActivity().findViewById(R.id.SDate);
DatePicker edateInput = (DatePicker) getActivity().findViewById(R.id.EDate);

final String strSdate = sdateInput.getDayOfMonth() + "/"
                + (sdateInput.getMonth() + 1) + "/" + sdateInput.getYear();
final String strEdate = edateInput.getDayOfMonth() + "/"
                + (edateInput.getMonth() + 1) + "/" + edateInput.getYear();

}else if(strEdate.compareTo(strSdate) < 0){
            //To check end date
            new AlertDialog.Builder(getActivity())
                    .setTitle("Confirmation")
                    .setMessage("Please Enter Valid End Date.")
                    .setNeutralButton("Back", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    // do nothing - it will just close when clicked
                                }
                            }).show();
        }

This validation works fine for certain dates only. I think strEdate.compareTo(strSdate) < 0 is wrong for date comparison. Can someone help me? Thanks :)


Solution

  • You're right, comparing Strings representing dates is not the correct way to perform date comparison. If you create Calendar objects from the input dates, the comparison is easier:

    Calendar startDate = Calendar.getInstance();
    Calendar endDate = startDate.clone();
    startDate.set(sdateInput.getYear(), sdateInput.getMonth(), sdateInput.getDayOfMonth(), 0, 0, 0);
    endDate.set(edateInput.getYear(), edateInput.getMonth(), edateInput.getDayOfMonth(), 0, 0, 0);
    
    if (startDate.after(endDate))
    {
          new AlertDialog.Builder(getActivity())
                    .setTitle("Confirmation")
                    .setMessage("Please Enter Valid End Date.")
                    .setNeutralButton("Back", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    // do nothing - it will just close when clicked
                                }
                            }).show();
    }
    

    As a clarification, the reason I'm cloning the startDate instead of doing Calendar.getInstance() again for the endDate is because calling .set(...) on a Calendar object will not update the milliseconds field. It's safer to use clone() so you know the only fields being factored into the comparison are the year, month and day.