11

I want to disable the dates before today date in the DatePickerDialog .I am new in android please suggest me how could i do this .Here is my code that i have written for DatePickerDialog

 final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                    int dayOfMonth) {
                // TODO Auto-generated method stub
                    myCalendar.set(Calendar.YEAR, year);
                    myCalendar.set(Calendar.MONTH, monthOfYear);
                    myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    updateLabel(val);
            }
        };
        depart.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    new DatePickerDialog(this, date, myCalendar
                            .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                            myCalendar.get(Calendar.DAY_OF_MONTH)).show();
                    val=1;
                }
            });

        returnDate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    new DatePickerDialog(this, date, myCalendar
                            .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                            myCalendar.get(Calendar.DAY_OF_MONTH)).show();
                            val=2;
                }
            });


private void updateLabel(int val) {

        String myFormat = "dd/MM/yy"; //In which you need put here
        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
        Log.d("Date vlue ", "==="+sdf.format(myCalendar.getTime()));
        if(val==1)
            depart.setText(sdf.format(myCalendar.getTime()));
        else
            returnDate.setText(sdf.format(myCalendar.getTime()));

        }

Please suggest me what have to do

Developer
  • 6,292
  • 19
  • 55
  • 115

5 Answers5

20

Get the DatePicker used in your DatePickerDialog with the getDatePicker() method and use the setMinDate(Long millis) method.

Pass to it the minimum date (in milliseconds from Epoch) you have to set.

So you can do something like

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d = sdf.parse("21/12/2012");
DatePicker datePicker = date.getDatePicker();
datePicker.setMinDate(d.getTime());

EDIT:

ok, so when your creating your DatePickerDialog, before showing it, just save it to a variable, set the minimum date and then show it.

DatePickerDialog dpd = new DatePickerDialog(IweenFlightSearch.this, date, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH));
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d = sdf.parse("21/12/2012");
dpd.getDatePicker().setMinDate(d.getTime());
dpd.show();

this should work.

Enrichman
  • 11,157
  • 11
  • 67
  • 101
  • i didn't got u where i have to make these changes so that the date before today will be disabled – Developer Jul 26 '13 at 10:42
  • You haven't post all your code, so it's hard to say "where" you have to make the changes. You should have somewhere a DatePickerDialog or a DatePicker. If you want further help you should show us where you're using those classes. – Enrichman Jul 26 '13 at 10:46
  • Please see in my question i have posted my complete code that i am using for datePickerDailog – Developer Jul 26 '13 at 10:50
  • I like this one a lot better than the accepted answer. Very clean and simple. – nasch Jan 04 '16 at 19:15
8

See this example..!

import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class MyAndroidAppActivity extends Activity {

    private TextView tvDisplayDate;

    private Button btnChangeDate;

    private int myear;
    private int mmonth;
    private int mday;

    static final int DATE_DIALOG_ID = 999;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        setCurrentDateOnView();
        addListenerOnButton();

    }

    // display current date
    public void setCurrentDateOnView() {

        tvDisplayDate = (TextView) findViewById(R.id.tvDate);       

        final Calendar c = Calendar.getInstance();
        myear = c.get(Calendar.YEAR);
        mmonth = c.get(Calendar.MONTH);
        mday = c.get(Calendar.DAY_OF_MONTH);

        // set current date into textview
        tvDisplayDate.setText(new StringBuilder()
                // Month is 0 based, just add 1
                .append(mmonth + 1).append("-").append(mday).append("-")
                .append(myear).append(" "));
    }

    public void addListenerOnButton() {

        btnChangeDate = (Button) findViewById(R.id.btnChangeDate);

        btnChangeDate.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                showDialog(DATE_DIALOG_ID);

            }

        });

    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            // set date picker as current date
            DatePickerDialog _date =   new DatePickerDialog(this, datePickerListener, myear,mmonth,
                    mday){
                @Override
                public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
                {   
                    if (year < myear)
                        view.updateDate(myear, mmonth, mday);

                    if (monthOfYear < mmonth && year == myear)
                        view.updateDate(myear, mmonth, mday);

                    if (dayOfMonth < mday && year == myear && monthOfYear == mmonth)
                        view.updateDate(myear, mmonth, mday);

                }
            };
            return _date;
        }
        return null;
    }

    private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

        // when dialog box is closed, below method will be called.
        public void onDateSet(DatePicker view, int selectedYear,
                int selectedMonth, int selectedDay) {
            myear = selectedYear;
            mmonth = selectedMonth;
            mday = selectedDay;

            // set selected date into textview
            tvDisplayDate.setText(new StringBuilder().append(mmonth + 1)
                    .append("-").append(mday).append("-").append(myear)
                    .append(" "));    

        }
    };

}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnChangeDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Date" />

    <TextView
        android:id="@+id/lblDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Current Date (M-D-YYYY): "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/tvDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>
Hariharan
  • 24,741
  • 6
  • 50
  • 54
  • disable dates before today date in DatePickerDialog. – Hariharan Jul 26 '13 at 11:14
  • I tried this it is allowing only to pick dates before today dates – Developer Jul 26 '13 at 11:24
  • I it is working now how could i implement this in my code because i have two calenders on my page – Developer Jul 26 '13 at 12:01
  • inside onclick listener write this line showDialog(DATE_DIALOG_ID); and add Dialog onCreateDialog() function... – Hariharan Jul 26 '13 at 12:22
  • 1
    Now it is working fine now the issue is that once user selects a date after that he can't select the date before that selected date – Developer Jul 26 '13 at 12:41
  • @Hari i want to show only 1 year calender from todays date.how we can do that – Developer Jul 29 '13 at 08:48
  • 1
    `Hariharan` Your code is working fine, but it doesn't seem to work when i install it on my phone. I mean previous dates are getting selected, which shouldn't happen right? How do i fix this? Thanks. – MetaldroiD Mar 19 '14 at 10:52
6

// Create a new instance of DatePickerDialog and return it

 DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), this,year,month,day);
            datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis());
            return datePickerDialog;
Dhara Patel
  • 359
  • 5
  • 19
4

I know it is too late. But hope this will helps. Use

date .getDatePicker().setMinDate(System.currentTimeMillis() - 1000);

in your case date is DatePickerDialog

Cheers!

KZoNE
  • 1,249
  • 1
  • 16
  • 27
  • 1
    Could you please explain the need of that minus 1000 – Arunkrishna Feb 09 '17 at 13:56
  • It works perfectly, thanks. Probably the -1000 is because you get the current time in milliseconds – Kzaf May 04 '17 at 01:31
  • 2
    Most likely because of this IllegalArgumentException issue. https://stackoverflow.com/questions/13661788/how-to-set-minimum-datepicker-date-to-current-date – Artemiy Jun 16 '17 at 14:52
2

I got the solution .hope it will help to someone static final int DATE_DIALOG_ID = 999;

depart.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    showDialog(DATE_DIALOG_ID);

                }
            });



protected Dialog onCreateDialog(int id) {
        final Calendar now = Calendar.getInstance();

        switch (id) {
        case DATE_DIALOG_ID:
            // set date picker as current date
            DatePickerDialog _date =   new DatePickerDialog(this, date,myCalendar
                    .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                    myCalendar.get(Calendar.DAY_OF_MONTH)){
                @Override
                public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
                {   
                    if (year < now.get(Calendar.YEAR))

                        view.updateDate(myCalendar
                                .get(Calendar.YEAR), myCalendar
                                .get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH));

                    if (monthOfYear < now.get(Calendar.MONTH) && year == now.get(Calendar.YEAR))
                        view.updateDate(myCalendar
                                .get(Calendar.YEAR), myCalendar
                                .get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH));

                    if (dayOfMonth < now.get(Calendar.DAY_OF_MONTH) && year == now.get(Calendar.YEAR) && 
                            monthOfYear == now.get(Calendar.MONTH))
                        view.updateDate(myCalendar
                                .get(Calendar.YEAR), myCalendar
                                .get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH));
                        }
            };
            return _date;
        }
        return null;
    }
Developer
  • 6,292
  • 19
  • 55
  • 115