在Android上使用带有日期选择器对话框的EditText

时间:2018-09-03 13:19:07

标签: android datepickerdialog

我是android的新手,我看着 herehere,但对我没用。感谢您的帮助。

我的问题是,我想在日期选择器对话框中设置以下约束。 1.如果所选日期小于当前日期,则会引发错误。和 2.选择的日期距离当前日期不得超过14天。

请参见下面的代码:

 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;
    }
}

第一个约束似乎只适用于年份而不是日期。例如。仅当我选择2019或2017时才有效。

1 个答案:

答案 0 :(得分:0)

尝试将"dd - mm - yyyy"更改为"dd - MM - yyyy"

mm-分钟

MM-几个月