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 for Android
  • Android Studio
  • Android Kotlin
  • Kotlin
  • Flutter
  • Dart
  • Android Project
  • Android Interview
Open In App
Next Article:
Date and Time Formatting in Android
Next article icon

Set MIN and MAX Selectable Dates in DatePicker Dialog in Android

Last Updated : 24 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 proceed. At this point, while picking up a date, the current calendar month or the nearest available date is generally displayed. However, not all the dates show availability for the slot. Knowingly, a past date is always greyed-out, meaning one cannot book a slot on a past date. Moreover, if the service provider has a limited number of slots or no slots for a particular day in the future, those dates are greyed-out. Similarly, the service providers may also take bookings for a range of dates, which they can facilitate accordingly. So in this article, we will show you how you could display a calendar and make a range of dates selectable in it. Follow the below steps once the IDE launches.

Step-by-Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

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"?> <RelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".MainActivity"> </RelativeLayout> 

Step 3: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin
import android.app.DatePickerDialog import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import java.util.*  class MainActivity : AppCompatActivity() {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)          // Get instance of calendar         // mCalendar will be set to current/today's date         val mCalendar = Calendar.getInstance()          // Creating a simple calendar dialog.            // It was 9 Aug 2021 when this program was developed.         val mDialog = DatePickerDialog(this, { _, mYear, mMonth, mDay ->             mCalendar[Calendar.YEAR] = mYear             mCalendar[Calendar.MONTH] = mMonth             mCalendar[Calendar.DAY_OF_MONTH] = mDay         }, mCalendar[Calendar.YEAR], mCalendar[Calendar.MONTH], mCalendar[Calendar.DAY_OF_MONTH])          // Changing mCalendar date from current to           // some random MIN day 15/08/2021 15 Aug 2021         // If we want the same current day to be the MIN day,           // then mCalendar is already set to today            // and the below code will be unnecessary         val minDay = 15         val minMonth = 8         val minYear = 2021         mCalendar.set(minYear, minMonth-1, minDay)         mDialog.datePicker.minDate = mCalendar.timeInMillis          // Changing mCalendar date from current to           // some random MAX day 20/08/2021 20 Aug 2021         val maxDay = 20         val maxMonth = 8         val maxYear = 2021         mCalendar.set(maxYear, maxMonth-1, maxDay)         mDialog.datePicker.maxDate = mCalendar.timeInMillis          // Display the calendar dialog         mDialog.show()      } } 
Java
import android.app.DatePickerDialog; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import java.util.Calendar;  public class MainActivity extends AppCompatActivity {      @Override     protected void onCreate(Bundle savedInstanceState)     {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          // Get instance of calendar         // mCalendar will be set to current/today's date         final Calendar mCalendar = Calendar.getInstance();          // Creating a simple calendar dialog.         // It was 9 Aug 2021 when this program was         // developed.         final DatePickerDialog mDialog             = new DatePickerDialog(                 this,                 new DatePickerDialog.OnDateSetListener() {                     @Override                     public void onDateSet(                         android.widget.DatePicker view,                         int mYear, int mMonth, int mDay)                     {                         mCalendar.set(Calendar.YEAR, mYear);                         mCalendar.set(Calendar.MONTH,                                       mMonth);                         mCalendar.set(Calendar.DAY_OF_MONTH,                                       mDay);                     }                 },                 mCalendar.get(Calendar.YEAR),                 mCalendar.get(Calendar.MONTH),                 mCalendar.get(Calendar.DAY_OF_MONTH));          // Changing mCalendar date from current to         // some random MIN day 15/08/2021 15 Aug 2021         // If we want the same current day to be the MIN         // day, then mCalendar is already set to today and         // the below code will be unnecessary         final int minDay = 15;         final int minMonth = 8;         final int minYear = 2021;         mCalendar.set(minYear, minMonth - 1, minDay);         mDialog.getDatePicker().setMinDate(             mCalendar.getTimeInMillis());          // Changing mCalendar date from current to         // some random MAX day 20/08/2021 20 Aug 2021         final int maxDay = 20;         final int maxMonth = 8;         final int maxYear = 2021;         mCalendar.set(maxYear, maxMonth - 1, maxDay);         mDialog.getDatePicker().setMaxDate(             mCalendar.getTimeInMillis());          // Display the calendar dialog         mDialog.show();     } } // This code is contributed by chinmaya121221 

Output:

You can see that we can select dates from a particular range only. The rest are greyed-out.


Next Article
Date and Time Formatting in Android
author
aashaypawar
Improve
Article Tags :
  • Kotlin
  • Android

Similar Reads

  • 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
  • Material Design Date Picker in Android
    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
    5 min read
  • Create Instruction Dialog in Android
    In most android applications, you must have seen that when you open a new app it shows some instructions to users about the features of their application. Here, we are going to implement the same. Here is a sample video of what we are going to build in this application. Note that we will be using Ja
    3 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
  • Date and Time Formatting in Android
    Date and Time in Android are formatted using the SimpleDateFormat library from Java, using Calendar instance which helps to get the current system date and time. The current date and time are of the type Long which can be converted to a human-readable date and time. In this article, it's been discus
    5 min read
  • Material Design Date Range 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
  • 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
  • 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
  • Alert Dialog with SingleItemSelection in Android
    Alert Dialogs are the UI elements that pop up when the user performs some crucial actions with the application. These window-like elements may contain multiple or single items to select from the list or have the error message and some action buttons. In this article, it's been discussed how to imple
    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
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