How to set the max and min date in Android Date Picker

In this android programming source code example, we are going to set the max and min date in Android Date Picker.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to set the max and min date in Android Date Picker.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ededed">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:layout_centerInParent="true"
        android:onClick="ShowDatePicker"
        android:text="ShowDatePicker"
        android:textColor="#ffffff"
        android:textSize="15sp"
        android:textStyle="bold" />

</RelativeLayout>

MainActivity.java

import android.app.DatePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;

import java.util.Calendar;

public class DatePickerAndTimePickerActivity10 extends AppCompatActivity {
    private int year, month, day;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_date_picker_and_time_picker10);
        //setting default date
        year = 2028;
        month = 4;
        day = 28;

    }

    public void ShowDatePicker(View view){
        DatePickerDialog dpd = new DatePickerDialog(DatePickerAndTimePickerActivity10.this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {

            }
        }, year, month, day);
        Calendar calendarmin = Calendar.getInstance();
        calendarmin.set(2019, 3, 31 );
        Calendar calendarmax = Calendar.getInstance();
        calendarmax.set(2019, 4, 31 );
        dpd.getDatePicker().setMinDate(calendarmin.getTimeInMillis());
        dpd.getDatePicker().setMaxDate(calendarmax.getTimeInMillis());
        dpd.show();
    }
}

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.