通过生日计算 年龄

复制代码
/**
     * 计算 年龄
     *
     * @param birthDate 生日
     * @return 岁数  当 生日 大于 当前时间时,返回 -1
     */
    public static int getAge(Date birthDate) {
        // 当前日历
        Calendar nowCalendar = Calendar.getInstance();
        // 生日大于当前日期
        if (nowCalendar.before(birthDate)) {
            return -1;
        }
        // 当前年月日
        int yearNow = nowCalendar.get(Calendar.YEAR);
        int monthNow = nowCalendar.get(Calendar.MONTH);
        int dayNow = nowCalendar.get(Calendar.DAY_OF_MONTH);
        // 出生日期年月日
        Calendar birthCalendar = Calendar.getInstance();
        birthCalendar.setTime(birthDate);
        int yearBirth = birthCalendar.get(Calendar.YEAR);
        int monthBirth = birthCalendar.get(Calendar.MONTH);
        int dayBirth = birthCalendar.get(Calendar.DAY_OF_MONTH);
        // 粗计算年龄
        int age = yearNow - yearBirth;
        // 当前月份小于出生月份年龄减一
        if (monthNow < monthBirth) {
            age--;
        }
        // 当前月份等于出生月份,日小于生日年龄减一
        else if (monthNow == monthBirth && dayNow < dayBirth) {
            age--;
        }
        // 返回年龄值
        return age;
    }
复制代码

 

本文作者:岁月记忆

本文链接:https://www.cnblogs.com/huang2979127746/p/17840595.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   岁月记忆  阅读(20)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起