码迷,mamicode.com
首页 > 编程语言 > 详细

java計算年齡的工具類

时间:2018-09-26 14:58:42      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:instance   返回   public   string   time   格式化   pre   当前时间   format   

整理一篇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計算年齡的工具類

标签:instance   返回   public   string   time   格式化   pre   当前时间   format   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!