我必须在日期字段中进行验证,必须比当前日期少18年,否则必须显示错误。
public static boolean dobdateValidate(String date) {
boolean result = false;
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
try {
Date parseddate = sdf.parse(date);
Calendar c2 = Calendar.getInstance();
c2.add(Calendar.DAY_OF_YEAR, -18);
Date dateObj2 = new Date(System.currentTimeMillis());
if (parseddate.before(c2.getTime())) {
result = true;
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
答案 0 :(得分:5)
您可以使用此方法来获得年龄
/**
* calculates age from birth date
*
* @param selectedMilli
*/
private void getAge(long selectedMilli) {
Date dateOfBirth = new Date(selectedMilli);
Calendar dob = Calendar.getInstance();
dob.setTime(dateOfBirth);
Calendar today = Calendar.getInstance();
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (today.get(Calendar.MONTH) < dob.get(Calendar.MONTH)) {
age--;
} else if (today.get(Calendar.MONTH) == dob.get(Calendar.MONTH)
&& today.get(Calendar.DAY_OF_MONTH) < dob
.get(Calendar.DAY_OF_MONTH)) {
age--;
}
if (age < 18) {
//do something
} else {
}
str_age = age + "";
Log.d("", getClass().getSimpleName() + ": Age in year= " + age);
}
答案 1 :(得分:3)
核心问题是Calendar.DAY_OF_YEAR
不正确,因为“[DAY_OF_YEAR表示]当前年份中的日期数字”。
改为使用Calendar.YEAR
。
其他建议:
dateObj2
变量,应将其删除。