1. 程式人生 > >java根據生日精確計算年齡

java根據生日精確計算年齡

dmi hda 日歷 tac day cat format oid trace

 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 }

java根據生日精確計算年齡