首页 > 代码库 > Java 计算年龄
Java 计算年龄
1 public static String getAgeTxt(String birthTime,String beginTime,int level){ 2 if(StringUtils.isBlank(birthTime)||StringUtils.isBlank(beginTime)){ 3 System.out.println("参数中有空值!"); 4 } 5 6 int year = 0,month=0,day=0,hour=0; 7 8 Date birthDate = getDateByString(birthTime,"yyyy-MM-dd HH:mm:ss"); 9 Date beginDate = getDateByString(beginTime,"yyyy-MM-dd HH:mm:ss"); 10 Calendar cBirthDate = Calendar.getInstance(); 11 Calendar cBeginDate = Calendar.getInstance(); 12 cBirthDate.setTime(birthDate); 13 cBeginDate.setTime(beginDate); 14 15 if(cBeginDate.get(Calendar.YEAR) < cBirthDate.get(Calendar.YEAR)){ 16 return "出生日期大于当前时间"; 17 } 18 19 //计算出生小时 20 if(cBeginDate.get(Calendar.HOUR_OF_DAY) < cBirthDate.get(Calendar.HOUR_OF_DAY)){ 21 hour = cBeginDate.get(Calendar.HOUR_OF_DAY)+24 - cBirthDate.get(Calendar.HOUR_OF_DAY); 22 day = day-1; 23 }else{ 24 hour = cBeginDate.get(Calendar.HOUR_OF_DAY) - cBirthDate.get(Calendar.HOUR_OF_DAY); 25 } 26 27 //计算出生日 28 if(cBeginDate.get(Calendar.DAY_OF_MONTH)<cBirthDate.get(Calendar.DAY_OF_MONTH)){ 29 day = day + cBeginDate.get(Calendar.DAY_OF_MONTH)+ cBirthDate.getActualMaximum(Calendar.DAY_OF_MONTH)-cBirthDate.get(Calendar.DAY_OF_MONTH); 30 month = month-1; 31 }else { 32 day = day + cBeginDate.get(Calendar.DAY_OF_MONTH)-cBirthDate.get(Calendar.DAY_OF_MONTH); 33 } 34 35 //计算出生月 36 if(cBeginDate.get(Calendar.MONTH) < cBirthDate.get(Calendar.MONTH)){ 37 month = month + cBeginDate.get(Calendar.MONTH)+12 - cBirthDate.get(Calendar.MONTH); 38 year = year -1; 39 }else{ 40 month = month + cBeginDate.get(Calendar.MONTH) - cBirthDate.get(Calendar.MONTH); 41 } 42 43 //计算出生年 44 year = year + cBeginDate.get(Calendar.YEAR) - cBirthDate.get(Calendar.YEAR); 45 46 if(year >7){ 47 return year+"岁"; 48 }else if (year >0 && year <7){ 49 if(month>0 && month <10){ 50 return year+"岁零"+month+"月"; 51 }else if(month >=10 ){ 52 return year+"岁"+month+"月"; 53 }else { 54 if(day>0){ 55 return year+"岁零"+day+"天"; 56 }else{ 57 return year+"岁"; 58 } 59 } 60 }else { 61 if(month >0){ 62 if( day >0 && day <10){ 63 return month+"个月零"+day+"天"; 64 }else if(day >=10){ 65 return month+"个月"+day+"天"; 66 }else{ 67 return month+"个月"; 68 } 69 }else{ 70 if(day >0){ 71 if( hour >0 && hour <10){ 72 return day+"天零"+hour+"小时"; 73 }else if(hour >=10){ 74 return day+"天"+hour+"小时"; 75 }else{ 76 return day+"天"; 77 } 78 }else{ 79 if(hour>0){ 80 return hour+"小时"; 81 }else{ 82 return "出生不足一小时"; 83 } 84 } 85 } 86 } 87 }
其中比较重要的几点
1、Calendar.getActualMaximum()计算对应的范围内最大值
2、计算年龄应该是从小到大计算年龄,这样方便计算后面的年龄(利用减法的原理);
Java 计算年龄
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。