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

java 出生日期 计算年龄

时间:2015-04-29 16:53:48      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

 1 public static int getAge(Date birthDay) throws Exception {
 2         Calendar cal = Calendar.getInstance();
 3 
 4         if (cal.before(birthDay)) {
 5             throw new IllegalArgumentException(
 6                 "The birthDay is before Now.It‘s unbelievable!");
 7         }
 8 
 9         int yearNow = cal.get(Calendar.YEAR);
10         int monthNow = cal.get(Calendar.MONTH);
11         int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
12         cal.setTime(birthDay);
13 
14         int yearBirth = cal.get(Calendar.YEAR);
15         int monthBirth = cal.get(Calendar.MONTH);
16         int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
17 
18         int age = yearNow - yearBirth;
19 
20         if (monthNow <= monthBirth) {
21             if (monthNow == monthBirth) {
22                 //monthNow==monthBirth
23                 if (dayOfMonthNow < dayOfMonthBirth) {
24                     age--;
25                 } else {
26                     //do nothing
27                 }
28             } else {
29                 //monthNow>monthBirth
30                 age--;
31             }
32         } else {
33             //monthNow<monthBirth
34             //donothing
35         }
36 
37         return age;
38     }

转载: http://www.blogjava.net/iamtin/archive/2006/03/10/34608.html

java 出生日期 计算年龄

标签:

原文地址:http://www.cnblogs.com/MDK-L/p/4466271.html

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