通过出生日期计算年龄,(birthday 为String ,length =10)有更简便的吗?
package com.cdu.dj.age;
import java.util.Calendar;
public class AgeUtil {
public static int age(String birthday){
//截取学生出生日期
String [] str = birthday.split("-");
int sYear = Integer.parseInt(str[0]);
int sMonth = Integer.parseInt(str[1]);
int sDay = Integer.parseInt(str[2]);
//获取当前年月日
Calendar cal = Calendar.getInstance();
int nowYear = cal.get(Calendar.YEAR);
int nowMonth = cal.get(Calendar.MONTH)+1;
int nowDay = cal.get(Calendar.DATE);
//当期-出生
int year = nowYear - sYear;
int month = nowMonth - sMonth;
int day = nowDay -sDay;
int age = year; // 大致赋值
if (year < 0) {// 选了未来的年份
age = 0;
} else if (year == 0) {// 同年的,要么为1,要么为0
if (month < 0) {// 选了未来的月份
age = 0;
} else if (month == 0) {// 同月份的
if (day < 0) {// 选了未来的日期
age = 0;
} else if (day>= 0) {
age = 1;
}
} else if (month > 0) {
age = 1;
}
} else if (year > 0) {
if (month < 0) {// 当前月>生日月
} else if (month == 0) {// 同月份的,再根据日期计算年龄
if (day < 0) {
} else if (day >= 0) {
age = age + 1;
}
} else if (month > 0) {
age = age + 1;
}
}
return age;
}
}