{"id":414,"date":"2019-10-06T17:32:57","date_gmt":"2019-10-06T07:32:57","guid":{"rendered":"https:\/\/learntodroid.com\/?p=414"},"modified":"2021-01-13T09:44:57","modified_gmt":"2021-01-12T23:44:57","slug":"how-to-disable-dates-in-a-datepicker-for-android","status":"publish","type":"post","link":"http:\/\/10.0.0.14:32769\/how-to-disable-dates-in-a-datepicker-for-android\/","title":{"rendered":"How to Disable Dates in a DatePicker for Android"},"content":{"rendered":"\n

When I have built Android apps in the past I have run into situations where I need to capture a date within the app from the user, like for example capturing the date for a customer’s appointment. Entering a date into a simple EditText field is not a great user experience so Android have created a DatePicker widget<\/a> that will present the user with a much nicer calendar display to cycle through the months and years and select a particular date from a given month.<\/p>\n\n\n\n

When getting the user to capture a date, you may want to restrict what dates in that calendar that they can select. Like if you want to capture a customer’s appointment date, they won’t be booking an appointment for a date that is already in the past. Rather than have the user select the date then validating the date and presenting the user with an error message if the date is not allowed to be chosen, what if there is a better way to disable dates such as dates in the past from being selected?<\/p>\n\n\n\n

The Android DatePicker allows you to prevent dates in the past from being selected by using the setMinDate(long minDate)<\/a> method. To disable dates in the past from being selected, follow the 2 steps below.<\/strong><\/p>\n\n\n\n

  1. Use the java.util.Calendar class to obtain the current date in milliseconds since January 1, 1970 using Calendar.getInstance().getTimeInMillis()<\/strong><\/li>
  2. Using the DatePicker created in the layout resource, use the setMinDate(long minDate) and pass the value above as a parameter<\/strong><\/li><\/ol>\n\n\n\n

    I have created a code sample below, which is also accessible on GitHub<\/a>, showing how to set a minimum date in the Android DatePicker<\/a>, where all dates before this minimum date will be disabled.<\/p>\n\n\n\n

    In addition to this, I have also researched how you could achieve the following with a DatePicker:<\/p>\n\n\n\n