根据生日计算年龄

时间:2022-01-27 00:36:14

根据生日计算年龄可以通过Calendar实现。最简单可以考虑get(Calendar.DAY_OF_YEAR)来简单修正年龄,但是遇到生日在闰年的2月29之后,或者今年是闰年的2月29之后可能出现计算不准,误差一天。所以还是老实判断年月日好了。
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) {
                
//monthNow==monthBirth
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age
--;
                } 
else {
                    
//do nothing
                }
            } 
else {
                
//monthNow>monthBirth
                age--;
            }
        } 
else {
            
//monthNow<monthBirth
            
//donothing
        }

        
return age;
    }