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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23762231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:25:27  来源:igfitidea点击:

How to disable past dates in Android date picker?

android

提问by Addy

How can I disable past dates in my Android date picker?

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

Here's the code that produces my DatePicker:

这是生成我的 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(" "));
    }
};

回答by Apoorv

You can do

你可以做

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

which sets today's date as minimum date and all the past dates are disabled.

它将今天的日期设置为最小日期,并且禁用所有过去的日期。

datePickeris an object of DatePickerif you are using an object of DatePickerDialogyou can do

datePicker是一个对象,DatePicker如果你正在使用DatePickerDialog你可以做的一个对象

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

Note: setMinDatewas introduced in API 11

注意:setMinDate在 API 11 中引入

回答by Arvin Jayanake

This method will work properly.

此方法将正常工作。

//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();

回答by Illegal Argument

This is how I do it:

这就是我的做法:

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

This is how you instantiate the 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);

This is my implementation feel free to change it. Note that this code sets mindate as currnet date by default. Also the newInstance is important.

这是我的实现,可以随意更改。请注意,此代码默认将 mindate 设置为当前日期。newInstance 也很重要。

回答by Ketan Ramani

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();

回答by Karan Chunara

You can use DatePicker#setMinDate() function to set a minimum date.

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

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

回答by Sikander Bhutto

You can use this line into your code...

您可以在代码中使用这一行...

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

回答by Pradeep Kumar Kushwaha

Ok so I am using MaterialDatePickerLibrary and its too simple to set minimum date on it.

好的,所以我正在使用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);

回答by asm1609

I had the same issue. Here is how i solved it.

我遇到过同样的问题。这是我解决它的方法。

Step 1: Declare click listener for opening the date picker.

第 1 步:声明用于打开日期选择器的单击侦听器。

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

Step 2: Declare a listener which listens for Date change.

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

Step 3: Now we need to declare a date picker dialog too inside the above showDateTimePicker() method. We will also be limiting the access to past dates in this step.

第 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();
        }

This is all that you need to do. Here is the final code that you may want to look:

这就是您需要做的所有事情。这是您可能想要查看的最终代码:

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

Hope it helps someone.

希望它可以帮助某人。

回答by Martin Gelevski

This depends on what you want to disable if you want to set to minimum date to be up to a couple of days then the best approach is to use LocalDateTime like this:

这取决于您想要禁用的内容,如果您想将最小日期设置为最多几天,那么最好的方法是像这样使用 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()

You set the new local date-time to be up to minus 30 days from nowand after that, you set in which time zone it needs to be for my example I am using "Europe/Berlin" time, you attach it to dpd.datePicker.minDate = ldt.toInstant(zoneOffSet).toEpochMilli()set to epochMilli and that's it

您将新的本地日期时间设置为从现在起最多负 30 天,之后,您设置它需要在哪个时区,例如我使用的是“欧洲/柏林”时间,然后将其附加到 dpd。 datePicker.minDate = ldt.toInstant(zoneOffSet).toEpochMilli()设置为 epochMilli 就是这样

回答by Gabriele Mariotti

With the Material Components Library just use the MaterialDatePickerand build your own DateValidatoror you can just use the DateValidatorPointForwardprovided by the library.

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

Something like:

就像是:

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

在此处输入图片说明