在验证出生日期时避免将来的日期

时间:2013-04-05 13:08:37

标签: android validation

我正试图以“MM / DD / YYYY”的形式出生,并且我想将“未来”日期视为无效。

到目前为止,这是我的代码:

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

我使用textview,但目前它接受“未来”日期。如何改进我的验证码?

1 个答案:

答案 0 :(得分:0)

在此处输入代码使用Calendar.after(日历)方法查看:http://developer.android.com/reference/java/util/Calendar.html#after(java.lang.Object)

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

boolean isAfterToday = selectedDate.after(c);