androiddatepickerdialog

Using EditText with date picker dialog on Android


I want to set the following constraint on my date picker dialog in Android:

  1. Throw error if selected date is less than current date. And
  2. Selected date must not exceed 14 days interval from current date.

I looked here and here but didn't work for me.

See my code below:

 private void pickUpDay() {
    final Calendar calendar = Calendar.getInstance();
    int mYear = calendar.get(Calendar.YEAR);
    int mMonth = calendar.get(Calendar.MONTH);
    int mDay = calendar.get(Calendar.DAY_OF_MONTH);

    final DatePickerDialog datePickerDialog = new DatePickerDialog(this,
            new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {


                    String stringDay = (dayOfMonth + " - " + (month + 1) + " - " + year);
                    SimpleDateFormat format = new SimpleDateFormat("dd - mm - yyyy", Locale.US);

                    try {
                        Date selectedDate = format.parse(stringDay);
                        Date currentDate = new Date(System.currentTimeMillis());


                        int dateDifference =
                                (int) getDateDiff(new SimpleDateFormat("dd - mm - yyyy", Locale.US),
                                currentDate.toString(), selectedDate.toString());

                        if (currentDate.compareTo(selectedDate) < 0 && dateDifference < 14) {
                            mBookDate.setText(stringDay);
                        } else {
                            Toast.makeText(BookDetails.this, "The selected date" +
                                            " is not valid!",
                                    Toast.LENGTH_SHORT).show();
                        }
                        System.out.println("days difference: " + dateDifference);
                        System.out.println("Get current Date: " + currentDate);
                        System.out.println("Get picker Date: " + selectedDate);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                }
            }, mYear, mMonth, mDay);
    datePickerDialog.show();
}

 //get days difference
public static long getDateDiff(SimpleDateFormat format, String currentDate, String newDate) {
    try {
        return TimeUnit.DAYS.convert(format.parse(newDate).getTime() -
                format.parse(currentDate).getTime(), TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

The first constraint seems to only work with the year and not days, e.g. it only works if I select 2019 or 2017.


Solution

  • Try to change "dd - mm - yyyy" to "dd - MM - yyyy"

    mm - minutes

    MM - months