日期比较以将用户限制为 select 直到当前日期

Date comparison to restrict user to select until current date

我的应用程序中有一个 DatePickerDialog,我希望用户选择的日期限制在当前日期之前。我将从 DatePickerDialog 中选择的日期与 newDate() 进行比较,如果选择的日期早于该日期,我将抛出一个错误。请查找代码如下

DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year,
                                          int monthOfYear, int dayOfMonth) {
                        Calendar calendar = Calendar.getInstance();
                        calendar.set(year, monthOfYear, dayOfMonth);
                        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
                        String visitDate = dateFormat.format(calendar.getTime());
                        try {
                            Date appointDate = dateFormat.parse(visitDate);
                            Date currentDate = new Date();
                            if(appointDate.before(currentDate)){
                                appointmentDateInputLayout.setError("Date selected is not within range!");
                            }else{
                                appointmentDateEditText.setText(visitDate);
                                appointmentDateInputLayout.setError(null);
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        appointmentDateEditText.setText(visitDate);
                    }
                }, mYear, mMonth, mDay);
        datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis());
        datePickerDialog.show();

但是当我这样做时,我在选择今天的日期时也遇到了错误。我希望用户允许当前日期。我在这里错过了什么?

请帮忙。

尝试与日历 getTime() 方法而不是当前日期进行比较。:

 If(appointDate.before(calendar.getTime())

看,

    Date currentDate = new Date() ;

在实例化时以毫秒为单位分配日期对象,因此交替分配并将日期对象放在代码的第一个位置会给出非常早的时间,因此您选择 visitdate 的时间会最终会更大(之后),因此 currentDate 中的毫秒数将小于 Picked new Date

中的毫秒数