如何在android中将datepicker对话框设置为昨天的日期

时间:2015-01-31 04:31:45

标签: android date datepicker

我有一个datepicker代码,用于将当前日期设置为datepicker对话框

我怎样才能将这个日期设置为昨天的日期,特别是在月末,它将保留昨天的日期和上个月,例如,如果在第一个小时我们检查它应该显示第31个月,从2月2日应显示第1个和等等。

 final Calendar c = Calendar.getInstance();
        maxyear = c.get(Calendar.YEAR);
        maxmonth = c.get(Calendar.MONTH);
        maxday = c.get(Calendar.DAY_OF_MONTH);


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

                    if (monthOfYear < 12 && year == 2014)
                        view.updateDate(2014, 12, mday);

                    if (dayOfMonth < 31 && year == 2014 && monthOfYear == 12)
                        view.updateDate(2014, 12, 31);

                    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);

                }
            };
            return _date;
        }
        return null;
    }

2 个答案:

答案 0 :(得分:2)

你试过这个吗?

Calendar now = Calendar.getInstance();   

now.add(Calendar.DATE, -1); 

int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH); // it's zero based
int day = now.get(Calendar.DAY_OF_MONTH);

DatePicker datePicker.updateDate(year, month, day);

答案 1 :(得分:1)

使用更新更新日期

mDatePicker.setTitle("Please select date");
mDatePicker.updateDate(1994, 6, 12);

// TODO Hide Future Date Here
                 mDatePicker.getDatePicker().setMaxDate(System.currentTimeMillis());