根据出生年月日计算年龄

private int countAge(String brithday){

    int age = 0;

    if(brithday != null && !brithday.isEmpty()){

            Date brithDate = DateUtil.format(birthday, DateUtil.YYYYMMDD);

            if(birthDate == null){

                return 0;

            }

            Calendar cal = Calendar.getInstance();
            int yearNow = cal.get(Calendar.YEAR);
            int monthNow = cal.get(Calendar.MONTH);
            int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
            
            cal.setTime(birthDate);
            int yearBirth = cal.get(Calendar.YEAR);
            int monthBirth = cal.get(Calendar.MONTH);
            int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

            // 计算年龄
            age = yearNow - yearBirth;
            if (monthNow <= monthBirth) {
                if (monthNow == monthBirth) {

                    if (dayOfMonthNow < dayOfMonthBirth)

                            age--;

                }else{
                    age--;
                }
            }
        }
        return age;

    }

}

猜你喜欢

转载自blog.csdn.net/zhang137107/article/details/79741041