根据出生日期计算年龄(精确到天)

/**
     * @Title:countAge
     * @Description:计算年龄
     * @param from  生日
     * @return String 返回类型
     */
    public static String countAge(Date from){
    String age = "";
int year = 0;
int month = 0;
int day = 0;
    if(from == null){
    age = age + 0;
    } else {
    Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        c1.setTime(from);
        c2.setTime(new Date());
        if (c1.after(c2)) {
        throw new IllegalArgumentException("生日不能超过当前日期");
            }
        int from_year = c1.get(Calendar.YEAR);
        int from_month = c1.get(Calendar.MONTH)+1;
        int from_day = c1.get(Calendar.DAY_OF_MONTH);
        System.out.println("以前:"+from_year + "-" + from_month + "-" + from_day);
        int MaxDayOfMonth = c1.getActualMaximum(Calendar.DAY_OF_MONTH);
        //System.out.println(MaxDayOfMonth);
        int to_year = c2.get(Calendar.YEAR);
        int to_month = c2.get(Calendar.MONTH)+1;
        int to_day = c2.get(Calendar.DAY_OF_MONTH);
        System.out.println("现在:"+to_year+"-"+to_month+"-"+to_day);
       
        year = to_year - from_year;
        if(c2.get(Calendar.DAY_OF_YEAR) - c1.get(Calendar.DAY_OF_YEAR) < 0){
        year = year -1;
        }
        if(year < 1){// 小于一岁要精确到月份和天数
        System.out.println("--------");
        if(to_month - from_month>0){
        month = to_month -from_month;
        if(to_day - from_day < 0){
        month = month - 1;
        day = to_day -from_day + MaxDayOfMonth;
        } else {
        day= to_day -from_day;
        }
        }else if(to_month - from_month==0){
          if(to_day - from_day > 0){
          day = to_day -from_day;
          }
        }
        }
        if(year > 1){
        age = age + year + "岁";
        }else if(month > 0) {
        age = age + month + "个月" + day + "天";
        } else {
        age=age + day + "天";
        }
    }
    //System.out.println(year + "--" + month + "--" + day);
    return age;
}

你可能感兴趣的:(java)