整理一篇Java計算年齡的工具類,方便實用

  public static int getAgeByBirth(String birthday) throws ParseException {
// 格式化传入的时间
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date parse = format.parse(birthday);
int age = 0;
try {
Calendar now = Calendar.getInstance();
now.setTime(new Date()); // 当前时间 Calendar birth = Calendar.getInstance();
birth.setTime(parse); // 传入的时间 //如果传入的时间,在当前时间的后面,返回0岁
if (birth.after(now)) {
age = 0;
} else {
age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
age += 1;
}
}
return age;
} catch (Exception e) {
return 0;
}
}

計算從一個時間到另一個時間的年份(年齡)場景:計算出生日期到出發時間的年齡:

   public static int getAgeByBirth(String birthday, String depatureTime) throws ParseException {
// 格式化传入的时间
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date parse = format.parse(birthday);
Date utilDate = format.parse(depatureTime);
int age = 0;
try {
Date date = new java.sql.Date(utilDate.getTime());
Calendar now = Calendar.getInstance();
now.setTime(date); // 当前时间 Calendar birth = Calendar.getInstance();
birth.setTime(parse); // 传入的时间 //如果传入的时间,在当前时间的后面,返回0岁
if (birth.after(now)) {
age = 0;
} else {
age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
age += 1;
} else if (now.get(Calendar.DAY_OF_YEAR) == birth.get(Calendar.DAY_OF_YEAR)) {
if (now.get(Calendar.DATE) > birth.get(Calendar.DATE)) {
age += 1;
}
}
}
return age;
} catch (Exception e) {
return 0;
}
}
04-13 16:24