2012-04-08 74 views
2

可能重複:
How do I calculate someone's age in Java?不返回正確的年齡?

我要計算用戶的年齡,我的方法犯規給出正確的年齡情況下,如果出生月份是等於當前的月份和出生當天小於或等於當天(如果用戶通過日期選擇器輸入他的出生日期爲9/4/1990或4/4/1990年齡將是21而不是22)我該如何解決這個問題?在這種情況下,我應該做些什麼來獲得正確的年齡?請幫我....

這是我的方法

public static String getAge(int year,int month,int day) { 
    Calendar dob = Calendar.getInstance(); 
    Calendar today = Calendar.getInstance(); 

    dob.set(year, month, day); 
    int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR); 

    if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)){ 
     age--; 
    } 
    Integer ageInt = new Integer(age); 
    String ageS = ageInt.toString(); 

    return ageS; 
} 

回答

4

有兩個問題與您的代碼:

  • 如果出生日期是9日1990年4月,你需要以dob.set(1990,3,9)作爲月份,從0開始==>您可能需要dob.set(year, month - 1, day);
  • 如果當前年份是閏年而不是出生年份(反之亦然),並且日期在28/29之後2月,你將在同一天獲得1天的差價。

這似乎是工作,但你應該用各種情景進行測試,並確保您滿意的結果:

public static String getAge(int year, int month, int day) { 
    Calendar dob = Calendar.getInstance(); 
    Calendar today = Calendar.getInstance(); 


    dob.set(year, month - 1, day); 

    int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR); 
    if (today.get(Calendar.MONTH) < dob.get(Calendar.MONTH)) { 
     age--; 
    } else if(today.get(Calendar.MONTH) == dob.get(Calendar.MONTH)) { 
     if (today.get(Calendar.DAY_OF_MONTH) < dob.get(Calendar.DAY_OF_MONTH)) { 
      age--; 
     } 
    } 

    Integer ageInt = new Integer(age); 
    String ageS = ageInt.toString(); 

    return ageS; 

} 

和A(非常簡單的)測試:

public static void main(String[] args) { //today = 8 April 2012 
    System.out.println(getAge(1990,3,7)); //22 
    System.out.println(getAge(1990,3,8)); //22 
    System.out.println(getAge(1990,3,9)); //22 
    System.out.println(getAge(1990,4,7)); //22 
    System.out.println(getAge(1990,4,8)); //22 
    System.out.println(getAge(1990,4,9)); //21 
    System.out.println(getAge(1990,5,7)); //21   
    System.out.println(getAge(1990,5,8)); //21   
    System.out.println(getAge(1990,5,9)); //21   
} 
+0

謝謝,我會嘗試第一個問題的解決方案,你能幫我解決第二個問題嗎?我應該添加到代碼中? – user 2012-04-08 21:35:53

+0

看到我編輯的答案的代碼 – assylias 2012-04-08 21:43:13

+0

謝謝verrrrrry很多幫助我 – user 2012-04-08 21:45:19

-2

例如,您可以通過轉換兩個日期(以毫秒爲單位並比日期對象)來計算差異。代碼會是這樣的:

long ageMilis = today.getTimeInMillis() - dob.getTimeInMillis(); 
Date age = new Date(ageMilis); 
return age.toString(); 
+2

你確定嗎? – Squonk 2012-04-08 21:41:04