java根据生日精确计算年龄

 1 package getAge;
 2 import java.text.SimpleDateFormat;
 3 import java.util.Calendar;
 4 import java.util.Date;
 5 
 6 /**
 7  * 根据用户生日精确计算年龄
 8  * 用Calender对象取得当前日期对象--从对象中分别取出年月日
 9  * @author Administrator
10  *
11  */
12 public class getAgeByBirthday{
13     public static int getAgeByBirth(Date birthday){        
14         //Calendar:日历
15         /*从Calendar对象中或得一个Date对象*/
16         Calendar cal = Calendar.getInstance();
17         /*把出生日期放入Calendar类型的bir对象中,进行Calendar和Date类型进行转换*/
18         Calendar bir = Calendar.getInstance();
19         bir.setTime(birthday);
20         /*如果生日大于当前日期,则抛出异常:出生日期不能大于当前日期*/
21         if(cal.before(birthday)){
22             throw new IllegalArgumentException("The birthday is before Now,It's unbelievable");
23         }
24         /*取出当前年月日*/
25         int yearNow = cal.get(Calendar.YEAR);
26         int monthNow = cal.get(Calendar.MONTH);
27         int dayNow = cal.get(Calendar.DAY_OF_MONTH);
28         /*取出出生年月日*/
29         int yearBirth = bir.get(Calendar.YEAR);
30         int monthBirth = bir.get(Calendar.MONTH);
31         int dayBirth = bir.get(Calendar.DAY_OF_MONTH);
32         /*大概年龄是当前年减去出生年*/
33         int age = yearNow - yearBirth;
34         /*如果出当前月小与出生月,或者当前月等于出生月但是当前日小于出生日,那么年龄age就减一岁*/
35         if(monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)){
36             age--;
37         }
38         return age;
39     }
40     /*main方法测试*/
41     public static void main(String[] args){
42         SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd");
43         String sftBirth = "1980-4-25";
44         Date date = null;
45         try{
46             date = sft.parse(sftBirth);
47         }catch(Exception e){
48             e.printStackTrace();
49         }
50         int age = getAgeByBirthday.getAgeByBirth(date);
51         System.out.print("年龄=" + age + "岁");
52     }
53 }