1.把出生日期字符串转换为日期格式。
public static Date parse(String strDate) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.parse(strDate);
}
2.计算年龄文章来源:https://www.toymoban.com/news/detail-514410.html
public static int getAge(Date birthDay) throws Exception {
Calendar cal = Calendar.getInstance();
if (cal.before(birthDay)) { //出生日期晚于当前时间,无法计算
throw new IllegalArgumentException(
"The birthDay is before Now.It's unbelievable!");
}
int yearNow = cal.get(Calendar.YEAR); //当前年份
int monthNow = cal.get(Calendar.MONTH); //当前月份
int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
cal.setTime(birthDay);
int yearBirth = cal.get(Calendar.YEAR);
int monthBirth = cal.get(Calendar.MONTH);
int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
int age = yearNow - yearBirth; //计算整岁数
if (monthNow <= monthBirth) {
if (monthNow == monthBirth) {
if (dayOfMonthNow < dayOfMonthBirth) age--;//当前日期在生日之前,年龄减一
}else{
age--;//当前月份在生日之前,年龄减一
} } return age; }
3.执行方法文章来源地址https://www.toymoban.com/news/detail-514410.html
public static void main(String[] args) {
try {
int age = getAge(parse("1990-09-27")); //由出生日期获得年龄***
System.out.println("age:"+age);
} catch (Exception e) {
e.printStackTrace();
}
}
到了这里,关于java 计算年龄 Java 根据出生日期计算年龄的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!