標籤:util maximum 最大 settime sed etag 出生日期 actual birt
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 計算年齡