美文网首页java
Java计算用生日计算年龄

Java计算用生日计算年龄

作者: HaleyLiu | 来源:发表于2017-10-08 09:06 被阅读21次

    用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;
         }
    

    相关文章

      网友评论

        本文标题:Java计算用生日计算年龄

        本文链接:https://www.haomeiwen.com/subject/frvsextx.html