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;
     }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章