Java 计算年龄

     public static String getAgeTxt(String birthTime,String beginTime,int level){
if(StringUtils.isBlank(birthTime)||StringUtils.isBlank(beginTime)){
System.out.println("参数中有空值!");
} int year = 0,month=0,day=0,hour=0; Date birthDate = getDateByString(birthTime,"yyyy-MM-dd HH:mm:ss");
Date beginDate = getDateByString(beginTime,"yyyy-MM-dd HH:mm:ss");
Calendar cBirthDate = Calendar.getInstance();
Calendar cBeginDate = Calendar.getInstance();
cBirthDate.setTime(birthDate);
cBeginDate.setTime(beginDate); if(cBeginDate.get(Calendar.YEAR) < cBirthDate.get(Calendar.YEAR)){
return "出生日期大于当前时间";
} //计算出生小时
if(cBeginDate.get(Calendar.HOUR_OF_DAY) < cBirthDate.get(Calendar.HOUR_OF_DAY)){
hour = cBeginDate.get(Calendar.HOUR_OF_DAY)+24 - cBirthDate.get(Calendar.HOUR_OF_DAY);
day = day-1;
}else{
hour = cBeginDate.get(Calendar.HOUR_OF_DAY) - cBirthDate.get(Calendar.HOUR_OF_DAY);
} //计算出生日
if(cBeginDate.get(Calendar.DAY_OF_MONTH)<cBirthDate.get(Calendar.DAY_OF_MONTH)){
day = day + cBeginDate.get(Calendar.DAY_OF_MONTH)+ cBirthDate.getActualMaximum(Calendar.DAY_OF_MONTH)-cBirthDate.get(Calendar.DAY_OF_MONTH);
month = month-1;
}else {
day = day + cBeginDate.get(Calendar.DAY_OF_MONTH)-cBirthDate.get(Calendar.DAY_OF_MONTH);
} //计算出生月
if(cBeginDate.get(Calendar.MONTH) < cBirthDate.get(Calendar.MONTH)){
month = month + cBeginDate.get(Calendar.MONTH)+12 - cBirthDate.get(Calendar.MONTH);
year = year -1;
}else{
month = month + cBeginDate.get(Calendar.MONTH) - cBirthDate.get(Calendar.MONTH);
} //计算出生年
year = year + cBeginDate.get(Calendar.YEAR) - cBirthDate.get(Calendar.YEAR); if(year >7){
return year+"岁";
}else if (year >0 && year <7){
if(month>0 && month <10){
return year+"岁零"+month+"月";
}else if(month >=10 ){
return year+"岁"+month+"月";
}else {
if(day>0){
return year+"岁零"+day+"天";
}else{
return year+"岁";
}
}
}else {
if(month >0){
if( day >0 && day <10){
return month+"个月零"+day+"天";
}else if(day >=10){
return month+"个月"+day+"天";
}else{
return month+"个月";
}
}else{
if(day >0){
if( hour >0 && hour <10){
return day+"天零"+hour+"小时";
}else if(hour >=10){
return day+"天"+hour+"小时";
}else{
return day+"天";
}
}else{
if(hour>0){
return hour+"小时";
}else{
return "出生不足一小时";
}
}
}
}
}

其中比较重要的几点

1、Calendar.getActualMaximum()计算对应的范围内最大值

2、计算年龄应该是从小到大计算年龄,这样方便计算后面的年龄(利用减法的原理);

上一篇:SharePoint 多行文本字段设置默认值


下一篇:SGU 194 Reactor Cooling Dinic求解 无源无汇有上下界的可行流