最代码官方的gravatar头像
最代码官方 2016-09-27 15:38:27

java根据出生年月日精确计算年龄的算法

今天项目中有个根据出生年月日,需要精确计算年龄的算法,找了半天才算有个正确的,分享出来给牛牛们成为自己java代码库的一部分算法。

public static int getAge(Date dateOfBirth) {
        int age = 0;
        Calendar born = Calendar.getInstance();
        Calendar now = Calendar.getInstance();
        if (dateOfBirth != null) {
            now.setTime(new Date());
            born.setTime(dateOfBirth);
            if (born.after(now)) {
                throw new IllegalArgumentException("年龄不能超过当前日期");
            }
            age = now.get(Calendar.YEAR) - born.get(Calendar.YEAR);
            int nowDayOfYear = now.get(Calendar.DAY_OF_YEAR);
            int bornDayOfYear = born.get(Calendar.DAY_OF_YEAR);
            System.out.println("nowDayOfYear:" + nowDayOfYear + " bornDayOfYear:" + bornDayOfYear);
            if (nowDayOfYear < bornDayOfYear) {
                age -= 1;
            }
        }
        return age;
    }

    public static void main(String[] args) throws Exception {
        SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date mydate = myFormatter.parse("2013-09-29");
        System.out.println(getAge(mydate));
    }

运行截图

java根据出生年月日精确计算年龄的算法


打赏

顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友