您好,欢迎来到化拓教育网。
搜索
您的当前位置:首页Java计算用生日计算年龄

Java计算用生日计算年龄

来源:化拓教育网

用util包下的Calender类来计算

public static Integer getAge(String birthday) throws Exception{
         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
         Date birth = df.parse(birthday);
         Calendar now = Calendar.getInstance();
         Calendar born = Calendar.getInstance();
         
         now.setTime(new Date());
         born.setTime(birth);
         
         if(born.after(now)){
             throw new IllegalArgumentException("Can't be born in the future"); 
         }
         
         int age = now.get(Calendar.YEAR)-born.get(Calendar.YEAR);
         if(now.get(Calendar.DAY_OF_YEAR) < born.get(Calendar.DAY_OF_YEAR)) {
             age -= 1;
         }
         return age;
     }

Copyright © 2019- huatuo9.cn 版权所有 赣ICP备2023008801号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务