之前项目中的年龄计算只是通过两个日期的年份相减,没有精确到天,导致生日的计算不精确。于是用Joda Time重新写了一下计算年龄的方法。年龄分周岁和虚岁,一般按周岁计算,因为周岁和生日有关。虚岁跟过年有关,一般不常用
之前的计算方法是这样的,使用Calendar类,只能说JDK里的日期api真是特别难用。
/**
*
* @param birth
* @return
*/
public static String getAgeFromBirth(String birth) {
if (birth == null || "".equals(birth)) {
return "";
}
String pattern = "yyyy-MM-dd";
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
try {
Date date = dateFormat.parse(birth);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int birthYear = calendar.get(Calendar.YEAR);
calendar.clear();
calendar.setTime(new Date());
int nowYear = calendar.get(Calendar.YEAR);
return (nowYear - birthYear) + "";
} catch (Exception e) {
e.printStackTrace();
}
return "0";
}
现在的计算方法,点进去看一下源码,这个Years.yearsBetween的方法是精确到毫秒的。
/**
*
* @param birth
* @return
*/
public static String getAgeFromBirth(String birth) {
if (birth == null || "".equals(birth)) {
return "";
}
DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd");
//时间解析
LocalDate birthday = DateTime.parse(birth, format).toLocalDate();
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthday, now);
return age.getYears() + "";
}
或者通过Joda Time的Period计算也行,可以选择PeriodType为yearMonthDay,精确到天
/**
*
* @param birth
* @return
*/
public static String getAgeFromBirth(String birth) {
if (birth == null || "".equals(birth)) {
return "";
}
DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd");
//时间解析
LocalDate birthday = DateTime.parse(birth, format).toLocalDate();
LocalDate now = new LocalDate();
Period period = new Period(birthday, now, PeriodType.yearMonthDay());
return period.getYears() + "";
}
网友评论