先从String类型的出生日期(“yyyy-MM-dd”)中提取int类型的年、月、日;再计算岁数。
程序如下:
/**
* 根据出生日期计算年龄的工具类BirthdayToAgeUtil
*/
public class BirthdayToAgeUtil { private static String birthday;
private static String ageStr;
private static int age;
//出生年、月、日
private static int year;
private static int month;
private static int day;
public static String BirthdayToAge(String birthday1) {
birthday = birthday1;
stringToInt(birthday, "yyyy-MM-dd");
// 得到当前时间的年、月、日
Calendar cal = Calendar.getInstance();
int yearNow = cal.get(Calendar.YEAR);
int monthNow = cal.get(Calendar.MONTH) + 1;
int dayNow = cal.get(Calendar.DATE);
KLog.d("yearNow:" + yearNow);
KLog.d("monthNow:" + monthNow);
KLog.d("dayNow:" + dayNow);
// 用当前年月日减去出生年月日
int yearMinus = yearNow - year;
int monthMinus = monthNow - month;
int dayMinus = dayNow - day;
age = yearMinus;// 先大致赋值
if (yearMinus <= 0) {
age = 0;
ageStr = String.valueOf(age) + "周岁啦!";
return ageStr;
}
if (monthMinus < 0) {
age = age - 1;
} else if (monthMinus == 0) {
if (dayMinus < 0) {
age = age - 1;
}
}
ageStr = String.valueOf(age) + "周岁啦!";
return ageStr;
} /**
* String类型转换成date类型
* strTime: 要转换的string类型的时间,
* formatType: 要转换的格式yyyy-MM-dd HH:mm:ss
* //yyyy年MM月dd日 HH时mm分ss秒,
* strTime的时间格式必须要与formatType的时间格式相同
*/
private static Date stringToDate(String strTime, String formatType) {
KLog.d("进入stringToDate");
try {
SimpleDateFormat formatter = new SimpleDateFormat(formatType);
Date date;
date = formatter.parse(strTime);
return date;
} catch (Exception e) {
return null;
}
} /**
* String类型转换为long类型
* .............................
* strTime为要转换的String类型时间
* formatType时间格式
* formatType格式为yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒
* strTime的时间格式和formatType的时间格式必须相同
*/
private static void stringToInt(String strTime, String formatType) {
KLog.d("进入stringToLong");
try {
//String类型转换为date类型
Calendar calendar = Calendar.getInstance();
Date date = stringToDate(strTime, formatType);
calendar.setTime(date);
KLog.d("调用stringToDate()获得的date:" + date);
if (date == null) {
} else {
//date类型转成long类型
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH) + 1;
day = calendar.get(Calendar.DAY_OF_MONTH);
}
} catch (Exception e) {
KLog.d("Exception:" + e);
}
}
}