How set maximum date in datepicker dialog in android?

AndroidAndroid Datepicker

Android Problem Overview


In my application am using date picker to set date.i want to set date picker maximum date is as today date according to system date.i don't know how to set date picker maximum date as today date.Can any one know help me to solve this problem.

My date picker coding is:

private int pYear;
private int pMonth;
private int pDay;
static final int DATE_DIALOG_ID = 0;

final Calendar c = Calendar.getInstance();
pYear = c.get(Calendar.YEAR);
pMonth = c.get(Calendar.MONTH);
pDay = c.get(Calendar.DAY_OF_MONTH);

// Date picker
public Dialog onCreateDialog(int id) {
	switch (id) {
	case DATE_DIALOG_ID:

		DatePickerDialog.OnDateSetListener pDateSetListener = new DatePickerDialog.OnDateSetListener() {

			public void onDateSet(DatePicker view, int year,
					int monthOfYear, int dayOfMonth) {

				pYear = year;
				pMonth = monthOfYear;
				pDay = dayOfMonth;

				e_dob.setText(new StringBuilder()
						// to set date in editext
						.append(pDay).append("/").append(pMonth + 1)
						.append("/").append(pYear).append(" "));
			}
		};
		return new DatePickerDialog(this, pDateSetListener, pYear, pMonth,
				pDay);

	}
	return null;
}

Android Solutions


Solution 1 - Android

Use setMaxDate().

For example, replace return new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay) statement with something like this:

    DatePickerDialog dialog = new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);
    dialog.getDatePicker().setMaxDate(new Date().getTime());
    return dialog;

Solution 2 - Android

Get today's date (& time) and apply them as maximum date.

Calendar c = Calendar.getInstance();
c.set(2017, 0, 1);//Year,Mounth -1,Day
your_date_picker.setMaxDate(c.getTimeInMillis());

ALSO WE MAY DO THIS (check this Stackoverflow answer for System.currentTimeMillis() vs Calendar method)

long now = System.currentTimeMillis() - 1000;
dp_time.setMinDate(now);
dp_time.setMaxDate(now+(1000*60*60*24*7)); //After 7 Days from Now

Solution 3 - Android

You can try replacing this line:

return new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);

By those:

DatePickerDialog dpDialog = new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);
DatePicker datePicker = dpDialog.getDatePicker();

Calendar calendar = Calendar.getInstance();//get the current day
datePicker.setMaxDate(calendar.getTimeInMillis());//set the current day as the max date
return dpDialog;

Solution 4 - Android

Try This

I have tried too many solutions but neither them was working,After wasting my half day finally i made a solution.

> This code simply show you a DatePickerDialog with Minimum and Maximum date,month and year,whatever you want just modify it.

final Calendar calendar = Calendar.getInstance();
                DatePickerDialog dialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker arg0, int year, int month, int day_of_month) {
                        calendar.set(Calendar.YEAR, year);
                        calendar.set(Calendar.MONTH, (month+1));
                        calendar.set(Calendar.DAY_OF_MONTH, day_of_month);
                        String myFormat = "dd/MM/yyyy";
                        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.getDefault());
                        your_edittext.setText(sdf.format(calendar.getTime()));
                    }
                },calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                dialog.getDatePicker().setMinDate(calendar.getTimeInMillis());// TODO: used to hide previous date,month and year
                calendar.add(Calendar.YEAR, 0);
                dialog.getDatePicker().setMaxDate(calendar.getTimeInMillis());// TODO: used to hide future date,month and year
                dialog.show();

Output:- Disable previous and future calendar

enter image description here

Solution 5 - Android

private int pYear;
private int pMonth;
private int pDay;
static final int DATE_DIALOG_ID = 0;
 
/**inside oncreate */
final Calendar c = Calendar.getInstance();
         pYear= c.get(Calendar.YEAR);
         pMonth = c.get(Calendar.MONTH);
         pDay = c.get(Calendar.DAY_OF_MONTH);


 @Override
     protected Dialog onCreateDialog(int id) {
             switch (id) {
             case DATE_DIALOG_ID:
                     return new DatePickerDialog(this,
                             mDateSetListener,
                             pYear, pMonth-1, pDay);
     		}
             
             return null;
     }
     protected void onPrepareDialog(int id, Dialog dialog) {
             switch (id) {
             case DATE_DIALOG_ID:
                     ((DatePickerDialog) dialog).updateDate(pYear, pMonth-1, pDay);
                     break;
             }
     }   
     private DatePickerDialog.OnDateSetListener mDateSetListener =
         new DatePickerDialog.OnDateSetListener() {
         public void onDateSet(DatePicker view, int year, int monthOfYear,
                         int dayOfMonth) {
        	 	// write your code here to get the selected Date
         }
 };

try this it should work. Thanks

Solution 6 - Android

use this code directly in main method hope it will help you...

@RequiresApi(api = Build.VERSION_CODES.N)       
public DatePickerDialog datePickerDialog_db()
{
       
	DatePickerDialog pickerDialog = new DatePickerDialog(getApplicationContext(),your view, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
	myCalendar.get(Calendar.DAY_OF_MONTH));
			
	pickerDialog.getDatePicker().setMaxDate(Calendar.getInstance().getTimeInMillis());
			
	pickerDialog.show();
			
	return null;       
}

Solution 7 - Android

Here's a Kotlin extension function:

fun EditText.transformIntoDatePicker(context: Context, format: String, maxDate: Date? = null) {
    isFocusableInTouchMode = false
    isClickable = true
    isFocusable = false

    val myCalendar = Calendar.getInstance()
    val datePickerOnDataSetListener =
        DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth ->
            myCalendar.set(Calendar.YEAR, year)
            myCalendar.set(Calendar.MONTH, monthOfYear)
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
            val sdf = SimpleDateFormat(format, Locale.UK)
            setText(sdf.format(myCalendar.time))
        }

    setOnClickListener {
        DatePickerDialog(
            context, datePickerOnDataSetListener, myCalendar
                .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
            myCalendar.get(Calendar.DAY_OF_MONTH)
        ).run {
            maxDate?.time?.also { datePicker.maxDate = it }
            show()
        }
    }
}

Usage:

In Activity:

editText.transformIntoDatePicker(this, "MM/dd/yyyy")
editText.transformIntoDatePicker(this, "MM/dd/yyyy", Date())

In Fragments:

editText.transformIntoDatePicker(requireContext(), "MM/dd/yyyy")
editText.transformIntoDatePicker(requireContext(), "MM/dd/yyyy", Date())

Solution 8 - Android

Check out my custom datepickerdialog

https://github.com/Redman1037/EightFoldsDatePickerDialog

import android.app.DatePickerDialog;
import android.content.Context;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;


/**
 * Created by Manohar on 14/08/2017.
 */

public class EightFoldsDatePickerDialog extends DatePickerDialog {


    private DatePickerDialog datePickerDialog;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");

    @RequiresApi(api = Build.VERSION_CODES.N)
    public EightFoldsDatePickerDialog(@NonNull Context context) {
        super(context);
        datePickerDialog = new DatePickerDialog(context);

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public EightFoldsDatePickerDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        datePickerDialog = new DatePickerDialog(context, themeResId);
    }

    public EightFoldsDatePickerDialog(@NonNull Context context, @Nullable OnDateSetListener listener, int year, int month, int dayOfMonth) {
        super(context, listener, year, month, dayOfMonth);
        datePickerDialog = new DatePickerDialog(context, listener, year, month, dayOfMonth);

    }

    public EightFoldsDatePickerDialog(@NonNull Context context, int themeResId, @Nullable OnDateSetListener listener, int year, int monthOfYear, int dayOfMonth) {
        super(context, themeResId, listener, year, monthOfYear, dayOfMonth);
        datePickerDialog = new DatePickerDialog(context, themeResId, listener, year, monthOfYear, dayOfMonth);
    }

    public void show() {
        datePickerDialog.show();
    }


    public void setMinDate(int year, int month, int day) {

        String minDate = "" + day + "-" + getmonth(month) + "-" + year;
 
        try {
            datePickerDialog.getDatePicker().setMinDate(dateFormat.parse(minDate).getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

    public void setMaxDate(int year, int month, int day) {

        String maxDate = "" + day + "-" + getmonth(month) + "-" + year;
        try {
            datePickerDialog.getDatePicker().setMaxDate(dateFormat.parse(maxDate).getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

    public void setTodayAsMaxDate() {
        
        datePickerDialog.getDatePicker().setMaxDate(Calendar.getInstance().getTime().getTime());

    }

    public void setTodayAsMinDate() {
        
        datePickerDialog.getDatePicker().setMinDate(Calendar.getInstance().getTime().getTime());

    }


    private String getmonth(int month) {

        switch (month) {
            case 1:
                return "January";

            case 2:
                return "February";

            case 3:
                return "March";

            case 4:
                return "April";

            case 5:
                return "May";

            case 6:
                return "June";

            case 7:
                return "July";

            case 8:
                return "August";

            case 9:
                return "September";

            case 10:
                return "October";

            case 11:
                return "November";

            case 12:
                return "December";


        }
        return "January";

    }

}

Usage

Copy EightFoldsDatePickerDialog.java to your project

EightFoldsDatePickerDialog datePickerDialog=new EightFoldsDatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
              //Do something with date
                Toast.makeText(this, "Year "+year+" month "+month+" day "+dayOfMonth, Toast.LENGTH_SHORT).show();
            }
        },year,month,day);   // give any  year , month , day values, this will be opened by default in dialog
        
        datePickerDialog.setMinDate(2017,8,7); //arguments are   year , month , date (use for setting custom min date)
        datePickerDialog.setMaxDate(2017,8,25);  //arguments are   year , month , date (use for setting custom max date)
        
       // datePickerDialog.setTodayAsMinDate();   // sets today's date as min date
       // datePickerDialog.setTodayAsMaxDate();    // sets today's date as max date
       
        datePickerDialog.show();

Result

https://user-images.githubusercontent.com/22935835/29265746-ccc8cbe4-80ff-11e7-8064-b478070c0de7.PNG" width="350"/>

Solution 9 - Android

private void selectDOB() {

    final Calendar calendar = Calendar.getInstance();
    mYear = calendar.get(Calendar.YEAR);
    mDay = calendar.get(Calendar.DATE);
    mMonth = calendar.get(Calendar.MONTH);

    DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
        @SuppressLint("LongLogTag")
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            strDateOfBirth = (month + 1) + "-" + dayOfMonth + "-" + year;

            //********************** check and set date with append 0 at starting***************************
            if (dayOfMonth < 10) {
                strNewDay = "0" + dayOfMonth;
            } else {
                strNewDay = dayOfMonth + "";
            }
            if (month + 1 < 10) {
                strNewMonth = "0" + (month + 1);
            } else {
                strNewMonth = (month + 1) + "";
            }

            Log.e("strnewDay *****************", strNewDay + "");
            Log.e("strNewMonth *****************", strNewMonth + "");

            //    etDateOfBirth.setText(dayOfMonth + " / " + (month + 1) + " / " + year);
            etDateOfBirth.setText(strNewDay + " / " + strNewMonth + " / " + year);

            Log.e("strDateOfBirth *******************", strDateOfBirth + "");

        }
    }, mYear, mMonth, mDay);

    datePickerDialog.show();

    //*************** input date of birth must be greater than or equal to 18 ************************************

    Calendar maxDate = Calendar.getInstance();
    maxDate.set(Calendar.DAY_OF_MONTH, mDay);
    maxDate.set(Calendar.MONTH, mMonth);
    maxDate.set(Calendar.YEAR, mYear - 18);
    datePickerDialog.getDatePicker().setMaxDate(maxDate.getTimeInMillis());

    //*************** input date of birth must be less than today date ************************************
    //   datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis());

}

Solution 10 - Android

      Calendar cal = Calendar.getInstance();
      datePickerDialog.getDatePicker().setMinDate(cal.getTimeInMillis());
    //To set make max 7days date selection on current year and month
    datePickerDialog.getDatePicker().setMaxDate((cal.getTimeInMillis())+(1000*60*60*24*6));

    datePickerDialog.setTitle("Select Date");
    datePickerDialog.show();

Solution 11 - Android

You can create Custom date picker, that is work for all api levels.

public class CustomDatePickerDialog extends DatePickerDialog {

    int maxYear;
    int maxMonth;
    int maxDay;

    public CustomDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
        super(context, callBack, year, monthOfYear, dayOfMonth);
    }

    public void setMaxDate(long maxDate) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            getDatePicker().setMaxDate(System.currentTimeMillis());
        } else {
            final Calendar c = Calendar.getInstance();
            c.setTimeInMillis(maxDate);
            maxYear = c.get(Calendar.YEAR);
            maxMonth = c.get(Calendar.MONTH);
            maxDay = c.get(Calendar.DAY_OF_MONTH);
        }
    }

    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            super.onDateChanged(view, year, monthOfYear, dayOfMonth);
        } else {
            if (year > maxYear)
                view.updateDate(maxYear, maxMonth, maxDay);

            if (monthOfYear > maxMonth && year == maxYear)
                view.updateDate(maxYear, maxMonth, maxDay);

            if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
                view.updateDate(maxYear, maxMonth, maxDay);
        }
    }

set max date

final CustomDatePickerDialog pickerDialog = new CustomDatePickerDialog(getActivity(),
        myDateListener, year, month, day);
pickerDialog.setMaxDate(System.currentTimeMillis());
pickerDialog.show();

Solution 12 - Android

i solved this by following

final Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = c.get(Calendar.DAY_OF_MONTH);
    datePickerDialog = new DatePickerDialog(getActivity(), this, year, month, day);
    datePickerDialog.getDatePicker().setMinDate(c.getTimeInMillis());    

hope it will help you

Solution 13 - Android

DatePicker dp = (DatePicker) findViewById(R.id.datePicker1);

dp.setMaxDate(new Date().getTime());
   

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYugeshView Question on Stackoverflow
Solution 1 - AndroidozbekView Answer on Stackoverflow
Solution 2 - Androidugali softView Answer on Stackoverflow
Solution 3 - AndroidYoann HercouetView Answer on Stackoverflow
Solution 4 - AndroidSunilView Answer on Stackoverflow
Solution 5 - AndroidAmit GuptaView Answer on Stackoverflow
Solution 6 - AndroidnagabrahmamView Answer on Stackoverflow
Solution 7 - AndroidDrunken DaddyView Answer on Stackoverflow
Solution 8 - AndroidManoharView Answer on Stackoverflow
Solution 9 - AndroidAnurag PandeyView Answer on Stackoverflow
Solution 10 - AndroidAbhay SarkarView Answer on Stackoverflow
Solution 11 - AndroidKishan VaghelaView Answer on Stackoverflow
Solution 12 - AndroidSultan AliView Answer on Stackoverflow
Solution 13 - AndroidVijesh KrishnaView Answer on Stackoverflow