0

I'm trying to Birthdate in the form of "MM/DD/YYYY", and I want to consider "future" dates to be invalid.

Here's my code so far:

final Calendar c = Calendar.getInstance();
mDay = c.get(Calendar.DAY_OF_MONTH);
mMonth = c.get(Calendar.MONTH);
mYear = c.get(Calendar.YEAR);

//String db=bdate.getText().toString();

bdate.setOnClickListener(new View.OnClickListener() {
  @Override
    public void onClick(View v) { 
      showDialog(DATE_DIALOG_ID);
    }
  });
  updateDisplay();
}

private void updateDisplay() {
  // TODO Auto-generated method stub
  this.bdate.setText(new StringBuilder()
  // Month is 0 based so add 1
  .append(mDay).append("-").append(mMonth + 1).append("-")
  .append(mYear).append(" "));
}

private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
  public void onDateSet(DatePicker view, int monthOfYear, int dayOfMonth,int year) {
    mDay = dayOfMonth;
    mMonth = monthOfYear;
    mYear = year;

    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(mDay, mMonth, mYear);

    updateDisplay();
  }
};

@Override
protected Dialog onCreateDialog(int id) {
  switch (id) {
    case DATE_DIALOG_ID:
      return new DatePickerDialog(this, mDateSetListener,mDay,mMonth,mYear);
    }
  return null;
 } 

I used textview, but at the moment it accepts "future" dates. How can I improve my validation code?

4

1 回答 1

0

这里输入代码看看使用Calendar.after(calendar)方法: http: //developer.android.com/reference/java/util/Calendar.html#after(java.lang.Object)

在您的 onDateSet 回调中,您可以使用返回的值来创建一个名为 selectedDate 的新日历对象。然后...

boolean isAfterToday = selectedDate.after(c);
于 2013-04-05T14:16:35.043 回答