如何在Android日期选择器中禁用过去的日期?

时间:2014-05-20 14:13:46

标签: android

如何在Android日期选择器中禁用过去日期?

这是生成我的DatePicker的代码:

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:
        // set date picker as current date
        return new DatePickerDialog(this, datePickerListener, year, month,
                day);
    }
    return null;
}

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int selectedYear,
            int selectedMonth, int selectedDay) {
        year = selectedYear;
        month = selectedMonth+1;
        day = selectedDay;

        startdate.setText(new StringBuilder().append(day).append("-")
                .append(getMonth(month + 1)).append("-").append(year)
                .append(" "));
    }
};

14 个答案:

答案 0 :(得分:178)

你可以做到

datePicker.setMinDate(System.currentTimeMillis() - 1000);

将今天的日期设为最低日期,所有过去日期均已停用。

datePickerDatePicker的对象,如果您使用DatePickerDialog的对象,则可以执行

datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);

注意:API {11}中引入了setMinDate

答案 1 :(得分:11)

此方法可以正常使用。

//Get yesterday's date
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -1);

//Set yesterday time milliseconds as date pickers minimum date
DatePickerDialog datePickerDialog = new DatePickerDialog(context, myDateListener, year, month, day);
datePickerDialog.getDatePicker().setMinDate(calendar.getTimeInMillis());
datePickerDialog.show();

答案 2 :(得分:8)

我就是这样做的:

public class DatePickerFragment extends DialogFragment {
OnDateSetListener ondateSet;
Calendar c;
int year = 0, month = 0, day = 0;

public DatePickerFragment() {
}

public void setCallBack(OnDateSetListener ondate) {
    ondateSet = ondate;
}

public static DatePickerFragment newInstance(Bundle bundle) {
    DatePickerFragment myFragment = new DatePickerFragment();
    myFragment.setArguments(bundle);
    return myFragment;
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // final Calendar c = Calendar.getInstance();
//if else for null arguments
    if (getArguments() != null) {
        year = getArguments().getInt("year");
        month = getArguments().getInt("month");
        day = getArguments().getInt("day");
        c = Calendar.getInstance();
        c.set(year, month, day);

    } else {
        c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);
        Log.d("else", "else");
    }


    DatePickerDialog picker = new DatePickerDialog(getActivity(),
            ondateSet, year, month, day);
    picker.getDatePicker().setMinDate(c.getTime().getTime());
    Log.d("picker timestamp", c.getTime().getTime() + "");
    return picker;
}
}

这是你实例化选择器的方法:

Bundle bundle = new Bundle();
        Calendar c = Calendar.getInstance();
        bundle.putInt("year", c.get(Calendar.YEAR));
        bundle.putInt("month", c.get(Calendar.MONTH));
        bundle.putInt("day", c.get(Calendar.DAY_OF_MONTH));
        DatePickerFragment fragment = DatePickerFragment
                .newInstance(bundle);
        fragment.setCallBack(dateSet);
        fragment.show(getActivity().getSupportFragmentManager(), null);

这是我的实现随时可以更改它。请注意,此代码默认情况下将mindate设置为currnet日期。新的实例也很重要。

答案 3 :(得分:5)

使用材料组件库,只需使用 MaterialDatePicker 并构建自己的DateValidator,或者您可以仅使用 DateValidatorPointForward 由图书馆提供。

类似的东西:

MaterialDatePicker.Builder<Long> builder = MaterialDatePicker.Builder.datePicker();

CalendarConstraints.DateValidator dateValidator = DateValidatorPointForward.now();
//if you need a custom date just use
//CalendarConstraints.DateValidator dateValidator = DateValidatorPointForward.from(yourDate);
constraintsBuilder.setValidator(dateValidator);
builder.setCalendarConstraints(constraintsBuilder.build());

MaterialDatePicker<Long> picker = builder.build();
picker.show(getSupportFragmentManager(), picker.toString());

enter image description here

答案 4 :(得分:2)

您可以将此行用于您的代码......

private Calendar cal;
private int day;
private int month;
private int year;

static final int DATE_PICKER_ID = 1111; 
TextView textView;

    textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            cal = Calendar.getInstance();
            day = cal.get(Calendar.DAY_OF_MONTH);
            month = cal.get(Calendar.MONTH);
            year = cal.get(Calendar.YEAR);
            showDialog(DATE_PICKER_ID);

        }
    });

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
        case DATE_PICKER_ID:
            // create a new DatePickerDialog with values you want to show

            DatePickerDialog datePickerDialog = new DatePickerDialog(this, datePickerListener, year, month, day);
            Calendar calendar = Calendar.getInstance();

            calendar.add(Calendar.DATE, 0); // Add 0 days to Calendar
            Date newDate = calendar.getTime();
            datePickerDialog.getDatePicker().setMinDate(newDate.getTime()-(newDate.getTime()%(24*60*60*1000)));
            return datePickerDialog;
    }
    return null;
}

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
    // the callback received when the user "sets" the Date in the
    // DatePickerDialog
    public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) {

        textViewTime.setText(selectedDay + "/" + (selectedMonth + 1) + "/" + selectedYear);
    }
};

答案 5 :(得分:2)

好的,我正在使用MaterialDatePicker库,它太简单了,无法设置最小日期。

DatePickerDialog mDatePickerDialog = DatePickerDialog.newInstance(listener,
                mTime.year, mTime.month, mTime.monthDay);
mDatePickerDialog.setYearRange(2016, 2036);
Calendar c = Calendar.getInstance();
c.setTimeInMillis(System.currentTimeMillis() - 1000);
mDatePickerDialog.setMinDate(c);

答案 6 :(得分:2)

我有同样的问题。以下是我如何解决它。

  

步骤1:声明点击监听器以打开日期选择器。

dateTime.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         showDateTimePicker();
     }
 });
  

步骤2:声明侦听日期更改的侦听器。

    public void showDateTimePicker(){
     final Calendar currentDate = Calendar.getInstance();
     date = Calendar.getInstance();
     DatePickerDialog.OnDateSetListener dateSetListener = new 
     DatePickerDialog.OnDateSetListener() {
     @Override
     public void onDateSet(DatePicker datePicker, int year, int 
     monthOfYear, int dayOfMonth) {
     date.set(year, monthOfYear, dayOfMonth);
    //use this date as per your requirement
     }
 };
}
  

步骤3:现在我们需要在上面的showDateTimePicker()方法中声明一个日期选择器对话框。我们还将在此步骤中限制对过去日期的访问。

          public void showDateTimePicker(){
             final Calendar currentDate = Calendar.getInstance();
             date = Calendar.getInstance();

            DatePickerDialog.OnDateSetListener dateSetListener = new 
            DatePickerDialog.OnDateSetListener() {
             @Override
             public void onDateSet(DatePicker datePicker, int year, int 
             monthOfYear, int dayOfMonth) {
             date.set(year, monthOfYear, dayOfMonth);

            //use this date as per your requirement
             }
         };
          DatePickerDialog datePickerDialog = new  
          DatePickerDialog(**Your Activity Name.this**, dateSetListener, 
          currentDate.get(Calendar.YEAR), 
          currentDate.get(Calendar.MONTH),   
          currentDate.get(Calendar.DAY_OF_MONTH));
        // Limiting access to past dates in the step below:
 datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
         datePickerDialog.show();
        }
  

这就是你需要做的一切。以下是您可能希望查看的最终代码:

    private Date date;

dateTime.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
             showDateTimePicker();
         }
     });



public void showDateTimePicker(){
 final Calendar currentDate = Calendar.getInstance();
date = Calendar.getInstance();

 DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
     @Override
     public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
         date.set(year, monthOfYear, dayOfMonth);

    //use this date as per your requirement
     }
 };
 DatePickerDialog datePickerDialog = new  DatePickerDialog(**Your Activity Name.this**, dateSetListener, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH),   currentDate.get(Calendar.DAY_OF_MONTH));
 datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
 datePickerDialog.show();
}

希望它有所帮助。

答案 7 :(得分:2)

您可以使用DatePicker#setMinDate()函数设置最小日期。

 datePickerDialog.getDatePicker().setMinDate(calendar.getTimeInMillis());

答案 8 :(得分:1)

这取决于您要禁用的内容,如果您希望将最短日期设置为最多两天,那么最好的方法是使用LocalDateTime,如下所示:

        val ldt: LocalDateTime = LocalDateTime.now().minusDays(30)
        val zone: ZoneId = ZoneId.of("Europe/Berlin")

        val zoneOffSet: ZoneOffset = zone.rules.getOffset(ldt)
        dpd.datePicker.minDate = ldt.toInstant(zoneOffSet).toEpochMilli()
        dpd.datePicker.maxDate = System.currentTimeMillis()
        dpd.show()

您将新的本地日期时间设置为最多从现在起减去30天,然后,您将其设置为我在我的示例中使用的“欧洲/柏林”的时间,您将其附加到 dpd.datePicker.minDate = ldt.toInstant(zoneOffSet).toEpochMilli() 设置为epochMilli就是这样

答案 9 :(得分:1)

科特林

直接转到日期选择器:

datePicker.minDate = System.currentTimeMillis()

如果您使用的是DatePickerDialog对象:

datePickerDialog.datePicker.minDate = System.currentTimeMillis()

答案 10 :(得分:1)

如果您使用的是 DatePicker

datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);

答案 11 :(得分:0)

Output

Calendar c = Calendar.getInstance();
DatePickerDialog dialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        String _year = String.valueOf(year);
        String _month = (month+1) < 10 ? "0" + (month+1) : String.valueOf(month+1);
        String _date = dayOfMonth < 10 ? "0" + dayOfMonth : String.valueOf(dayOfMonth);
        String _pickedDate = year + "-" + _month + "-" + _date;
        Log.e("PickedDate: ", "Date: " + _pickedDate); //2019-02-12
    }
}, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.MONTH));
dialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
dialog.show();

答案 12 :(得分:0)

如果这是您的日期选择器(来自我自己现有项目的代码)

   <DatePicker
                android:id="@+id/date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="17dp"
                android:layout_marginTop="20dp"
                android:layout_marginEnd="17dp"
                android:layout_marginBottom="31dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/outlinedTextField"
                android:datePickerMode="calendar"/>

引用 DatePicker 如下:

 private DatePicker date;

在适当的方法中根据片段或活动是否初始化它

  date = view.findViewById(R.id.date);

在选择数据或提交之前,请确保禁用过去的日期(今天之前的日期或根据您的需要),例如

     // disable date before today
    Calendar today = Calendar.getInstance();
    long now = today.getTimeInMillis();
    date.setMinDate(now);

现在所有过去的日期都将被禁用,这意味着它们将无法选择。那应该可行。

答案 13 :(得分:0)

如果你使用的是`DatePickerDialog

datePicker.setMinDate(System.currentTimeMillis() - 1000);

这将禁用过去的日期。