首页 > 编程语言 > 详细

java計算年齡的工具類

时间:2018-09-26 14:44:57      阅读:155      评论:0      收藏:0      [点我收藏+]

整理一篇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         }

 

java計算年齡的工具類

原文:https://www.cnblogs.com/javallh/p/9706727.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!