美文网首页
根据出生日期计算年龄

根据出生日期计算年龄

作者: writeanewworld | 来源:发表于2021-07-09 17:08 被阅读0次

/**
     * 根据出生日期计算年龄.
     * @param birthDay 出生日期
     * @return 年龄
     */
    public int getAge(Date birthDay) {
        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;
    }

相关文章

网友评论

      本文标题:根据出生日期计算年龄

      本文链接:https://www.haomeiwen.com/subject/rnzoultx.html