欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-03 19:37:24
@根据出生日期计算年龄(精确到天)代码块public class CountAgeUtil { public static String countAge(String from){ String age = ""; int year = 0; int month = 0; int day = 0; from = from.substring(0, 10).replace("-", ""); int...

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

public class CountAgeUtil {
    public static String countAge(String from){
        String age = "";
        int year = 0;
        int month = 0;
        int day = 0;
        from = from.substring(0, 10).replace("-", "");
        int birthYear = Integer.parseInt(from.substring(0, 4));
        int birthMonth = Integer.parseInt(from.substring(4, 6))-1;
        int birthDay = Integer.parseInt(from.substring(6, 8));
        Calendar birthday = new GregorianCalendar(birthYear, birthMonth, birthDay);
        if(from == null){
            age = age + 0;
        } else {
            Calendar c1 =  new GregorianCalendar(birthYear, birthMonth, birthDay);
            Calendar c2 = Calendar.getInstance();
            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);
            int MaxDayOfMonth = c1.getActualMaximum(Calendar.DAY_OF_MONTH);
            int to_year = c2.get(Calendar.YEAR);
            int to_month = c2.get(Calendar.MONTH)+1;
            int to_day = c2.get(Calendar.DAY_OF_MONTH);
            year = to_year - from_year;
            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){
                    --year;
                    month = 11;
                    day = to_day -from_day + MaxDayOfMonth;
                } else {
                    day= to_day -from_day;
                }
            }else if(to_month-from_month<0){
                --year;
                month = to_month -from_month+12;
                if(to_day - from_day < 0){
                    month = month - 1;
                    day = to_day -from_day + MaxDayOfMonth;
                } else {
                    day= to_day -from_day;
                }

            }
            age=age + year + "岁"+month + "个月" + day + "天";
        }
        return age;
    }
}

本文地址:https://blog.csdn.net/weixin_43865707/article/details/111991845

相关标签: java