java計算年齡的工具類

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

 1  public static int getAgeByBirth(String birthday) throws ParseException {
 2             // 格式化传入的时间
 3             SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
 4             Date parse = format.parse(birthday);
 5             int age = 0;
 6             try {
 7                 Calendar now = Calendar.getInstance();
 8                 now.setTime(new Date()); // 当前时间
 9 
10                 Calendar birth = Calendar.getInstance();
11                 birth.setTime(parse); // 传入的时间
12 
13                 //如果传入的时间,在当前时间的后面,返回0岁
14                 if (birth.after(now)) {
15                     age = 0;
16                 } else {
17                     age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
18                     if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
19                         age += 1;
20                     }
21                 }
22                 return age;
23             } catch (Exception e) {
24                 return 0;
25             }
26         }

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

 1   public static int getAgeByBirth(String birthday, String depatureTime) throws ParseException {
 2         // 格式化传入的时间
 3         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
 4         Date parse = format.parse(birthday);
 5         Date utilDate = format.parse(depatureTime);
 6         int age = 0;
 7         try {
 8             Date date = new java.sql.Date(utilDate.getTime());
 9             Calendar now = Calendar.getInstance();
10             now.setTime(date); // 当前时间
11 
12             Calendar birth = Calendar.getInstance();
13             birth.setTime(parse); // 传入的时间
14 
15             //如果传入的时间,在当前时间的后面,返回0岁
16             if (birth.after(now)) {
17                 age = 0;
18             } else {
19                 age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
20                 if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
21                     age += 1;
22                 } else if (now.get(Calendar.DAY_OF_YEAR) == birth.get(Calendar.DAY_OF_YEAR)) {
23                     if (now.get(Calendar.DATE) > birth.get(Calendar.DATE)) {
24                         age += 1;
25                     }
26                 }
27             }
28             return age;
29         } catch (Exception e) {
30             return 0;
31         }
32     }
原文地址:https://www.cnblogs.com/javallh/p/9706727.html