android根据身份证计算年龄

//由出生日期获得年龄
    public static   int getAge(Date birthDay, Context context) {
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) {
            Toast.makeText(context, "出生日期不能在当今日期之后!", Toast.LENGTH_SHORT).show();
            return -1;
        }
        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;
    }

你可能感兴趣的:(android根据身份证计算年龄)