首页 > 解决方案 > What, exactly, does Android DatePicker.setMinDate() and DatePicker.setMaxDate() do?

问题描述

I am working on an app in which I would like the user to select dates, so I am using the DatePickerDialog.

I want the user to be able to select dates only within a certain range, so I figured I would use the DatePicker.setMinDate() and DatePicker.setMaxDate() methods to limit their choices. This is what I used:

DatePickerDialog datePickerDialog = new DatePickerDialog(this);
datePickerDialog.getDatePicker().setMinDate(viewModel.getMinDate().toEpochSecond());
datePickerDialog.getDatePicker().setMaxDate(viewModel.getMaxDate().toEpochSecond());
datePickerDialog.show();

In a particular instance of my app, the viewModel.getMinDate().toEpochSecond() gives me 2019-07-15T18:18:44.829Z, and the viewModel.getMaxDate().toEpochSecond() gives me 2019-07-16T15:12:39.563Z, which are both valid (type Long) dates of 1563214724 and 1563289959 respectively.

However, when my DatePicker dialog opens, I get this:

enter image description here

I cannot select any dates whatsoever.

If, however, I were to try this:

DatePickerDialog datePickerDialog = new DatePickerDialog(this);
datePickerDialog.getDatePicker().setMinDate(new Date().getTime());
datePickerDialog.getDatePicker().setMaxDate(new Date().getTime() + 1000L);
datePickerDialog.show();

I get this:

enter image description here

Again, still cannot select any dates.

Date inconsistencies aside, I do not see how setMinDate() and setMaxDate() are affecting anything at all. I am still able to select dates outside of my min and max range. Reading the developer reference, it says:

Sets the minimal date supported by this NumberPicker in milliseconds since January 1, 1970 00:00:00 in TimeZone#getDefault() time zone.

What does that even mean "supported by this NumberPicker"??? Obviously, it doesn't mean "limits what a user can and cannot pick" as I cannot pick anything anyway.

So, again, what, exactly, does DatePicker.setMinDate() and DatePicker.setMaxDate() do?


EDIT:

Thanks to @MobileMon this is the solution that I used:

Calendar calendar = Calendar.getInstance();
calendar.set(minDate.getYear(), (minDate.getMonthValue() - 1), minDate.getDayOfMonth());
return calendar.getTimeInMillis();

标签: androidandroid-datepicker

解决方案


Your min and max dates are not even a day a part (2019-07-15 & 2019-07-16). There's no choice for the user to make. Need to make a greater range for date picking.

In the second example where you say new Date().getTime(), same scenario. Try setting it to like '9/7/2016' - '12/3/2019' for example


推荐阅读