Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android DatePicker Date Limiting

I am using DatePicket in my activity ,

I want to limit the date picked by user to todays date.

They should not able to select date greater than todays date.

thank you.

like image 676
Ganapathy C Avatar asked Feb 09 '11 10:02

Ganapathy C


2 Answers

yes you can do it very easely the validation here is the exemple:

if(dateObj1.before(dateObj2) || dateObj1.equals(dateObj2)){
//the program runs normally
}
else{
                new AlertDialog.Builder(PM_Edit.this)

                .setTitle("Wrong Data Input!")

                .setMessage("The end Date must be Before the start Date, please insert new Date values")

                .setNeutralButton("Ok",

                new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog,

                int which) {

                }

                }).show();
            }

Credits to: http://www.brighthub.com/mobile/google-android/articles/41545.aspx

like image 126
Schewns Avatar answered Sep 21 '22 14:09

Schewns


DatePicker datePicker = (DatePicker)findViewById(R.id.new_date_picker);


datePicker.init(year, month, day, new OnDateChangedListener() {

    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear,int dayOfMonth) {

        if(isDateAfter(view)){
            Calendar mCalendar = Calendar.getInstance();
            view.init(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), this);
        }
    }


    private boolean isDateAfter(DatePicker tempView) {
        Calendar mCalendar = Calendar.getInstance();
        Calendar tempCalendar = Calendar.getInstance();
        tempCalendar.set(tempView.getYear(), tempView.getMonth(), tempView.getDayOfMonth(), 0, 0, 0);
        if(tempCalendar.after(mCalendar))
            return true;
        else 
            return false;
    }
});
like image 45
Hitesh Sondhi Avatar answered Sep 23 '22 14:09

Hitesh Sondhi