Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Find Days Between Two Dates in Android
Next article icon

How to Disable Previous or Future Dates in Datepicker in Android?

Last Updated : 26 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we are going to disable previous or future dates in Datepicker. Most of the time when we use DatePicker in Android we see that all the date in that is enabled. We can select any of the dates. But here we are going to see how to disable past or future dates. Disabling the Past Date can be useful when we are assigning tasks to someone. Then the selected date must be in the future. Disabling the Previous Date can be useful when we are asking for the date of birth for someone. Then the selected date must be in past. Let's implement this feature. 

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML
<?xml version="1.0" encoding="utf-8"?> <LinearLayout      xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:gravity="center"     android:orientation="vertical"     tools:context=".MainActivity">      <EditText         android:id="@+id/edittext"         android:layout_width="match_parent"         android:layout_height="wrap_content" />      </LinearLayout> 

Step 3: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. 

For Max Date:

Get the DatePicker from DatePickerDialog with getDatePicker(). Set the max date to the current date with setMaxDate(): 

Note: Requires API level 11.

datePicker.getDatePicker().setMaxDate(calendar.getTimeInMillis());

Below is the code for the MainActivity.java file.  

Java
import android.app.DatePickerDialog; import android.os.Build; import android.os.Bundle; import android.view.View; import android.widget.EditText;  import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity;  import java.util.Calendar;  public class MainActivity extends AppCompatActivity {      EditText editText;     DatePickerDialog datePicker;      @RequiresApi(api = Build.VERSION_CODES.N)     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);                  // initialising the calendar         final Calendar calendar = Calendar.getInstance();                  // initialising the layout         editText = findViewById(R.id.edittext);         final int day = calendar.get(Calendar.DAY_OF_MONTH);         final int year = calendar.get(Calendar.YEAR);         final int month = calendar.get(Calendar.MONTH);                  // initialising the datepickerdialog         datePicker = new DatePickerDialog(MainActivity.this);                  // click on edittext to set the value         editText.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                 datePicker = new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {                     @Override                     public void onDateSet(android.widget.DatePicker view, int year, int month, int dayOfMonth) {                         // adding the selected date in the edittext                         editText.setText(dayOfMonth + "/" + (month + 1) + "/" + year);                     }                 }, year, month, day);                                  // set maximum date to be selected as today                 datePicker.getDatePicker().setMaxDate(calendar.getTimeInMillis());                                  // show the dialog                 datePicker.show();             }         });     } } 

For min Date:

Similarly, Get the DatePicker from DatePickerDialog with getDatePicker(). Set the min date to the current date with setMinDate():    

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

Below is the code for the MainActivity.java file.  

Java
import android.app.DatePickerDialog; import android.os.Build; import android.os.Bundle; import android.view.View; import android.widget.EditText;  import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity;  import java.util.Calendar;  public class MainActivity extends AppCompatActivity {      EditText editText;     DatePickerDialog datePicker;      @RequiresApi(api = Build.VERSION_CODES.N)     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          // initialising the calendar         final Calendar calendar = Calendar.getInstance();          // initialising the layout         editText = findViewById(R.id.edittext);         final int day = calendar.get(Calendar.DAY_OF_MONTH);         final int year = calendar.get(Calendar.YEAR);         final int month = calendar.get(Calendar.MONTH);          // initialising the datepickerdialog         datePicker = new DatePickerDialog(MainActivity.this);          // click on edittext to set the value         editText.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                 datePicker = new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {                     @Override                     public void onDateSet(android.widget.DatePicker view, int year, int month, int dayOfMonth) {                         // adding the selected date in the edittext                         editText.setText(dayOfMonth + "/" + (month + 1) + "/" + year);                     }                 }, year, month, day);                  // set maximum date to be selected as today                 datePicker.getDatePicker().setMinDate(calendar.getTimeInMillis());                  // show the dialog                 datePicker.show();             }         });     } } 

Output: 


 


Next Article
Find Days Between Two Dates in Android

A

annianni
Improve
Article Tags :
  • Java
  • Android
  • Android-Date-time
Practice Tags :
  • Java

Similar Reads

  • Set MIN and MAX Selectable Dates in DatePicker Dialog in Android
    Applications like ticket booking for traveling, theatres, movies, plays, appointments, reminders, etc., require the user to pick a specific day or time for confirming a slot or a booking. In most of these applications, a service is to be picked and then the user has to pick up a slot to further proc
    4 min read
  • How to PopUp DatePicker While Clicking on EditText in Android?
    In android applications date pickers are used to pick the date from the calendars and display them within our text view. Many times we have to display this date picker dialog box by clicking on edit text and then we have to display that date within our edit text. In this article, we will take a look
    4 min read
  • Find Days Between Two Dates in Android
    There are many travels and accommodation-based Android applications which we use to check and buy tickets for any traveling and hotel booking. Inputs such as origin, traveling destination, selection of hotel, and trip dates are needed to book appropriate options. In the case of hotel booking, the nu
    3 min read
  • How to Get Current Time and Date in Android?
    Many times in android applications we have to capture the current date and time within our android application so that we can update our date according to that. In this article, we will take a look at How to get the current Time and Date in our android application.  Note: This Android article covere
    3 min read
  • DatePickerDialog in Android
    Android DatePicker is a user interface control that is used to select the date by day, month, and year in the android application. DatePicker is used to ensure that the users will select a valid date. In android DatePicker having two modes, the first one shows the complete calendar and the second on
    4 min read
  • How to Implement Date Range Picker in Android?
    Date Range Picker is a widely used feature in many popular Android apps and an essential component of Material Design. It allows users to select a range of dates such as a start and end date for various purposes including scheduling, filtering data, and setting time boundaries. Some Of The Real Life
    4 min read
  • How to Implement Custom Calendar in Android?
    Nowadays in most of the apps, we see Calendar in most of the apps for displaying birth dates or for any appointment application. Displaying the date in the app with the help of the Calendar view gives a better user experience. In this article, we are going to make a custom calendar for our android a
    4 min read
  • How to Build Age Calculator in Android Studio?
    Hello geeks, today we are going to make an application to calculate Age or time period between two dates. By making this application one can calculate his/her exact age, also one can calculate the exact difference between two dates. Prerequisites: Before making this application, you can go through t
    6 min read
  • More Functionalities of Material Design Date Picker in Android
    As discussed in the Material Design Date Picker in Android it offers many functionalities to users and is easy to implement for developers. So in this article, we are going to discuss more functionalities of material design date picker with examples. Note that the UI part will be the same as in the
    12 min read
  • Material Design Date Picker in Android using Kotlin
    Material Design Components (MDC Android) offers designers and developers a way to implement Material Design in their Android applications. Developed by a core team of engineers and UX designers at Google, these components enable a reliable development workflow to build beautiful and functional Andro
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences