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;
     }
发布了30 篇原创文章 · 获赞 39 · 访问量 2051

猜你喜欢

转载自blog.csdn.net/weixin_44564242/article/details/105228367