2008-09-03 88 views

回答

12

我在the bottom of this page in comments section (which is now offline)找到答案。

jpwrunyan上二零零七年四月三十日說在10:10 PM:

順便說一句,這裏是如何計算年齡在幾年(只)從出生日期,而無需考慮的飛躍年:

Fine-Wei Lin出現小幅回調,該代碼讀取

private function getYearsOld(dob:Date):uint { 
    var now:Date = new Date(); 
    var yearsOld:uint = Number(now.fullYear) - Number(dob.fullYear); 
    if (dob.month > now.month || (dob.month == now.month && dob.date > now.date)) 
    { 
     yearsOld--; 
    } 
    return yearsOld; 
} 

這可以處理大多數需要計算年齡的情況。

1

你也可以做到這一點大致相同,討論here:(翻譯爲AS3)

var age:int = (new Date()).fullYear - bDay.fullYear; 
if ((new Date()) < (new Date((bDay.fullYear + age), bDay.month, bDay.date))) age--; 
1

這裏是一個小更復雜的計算,這種計算年數和月的年齡。例如:用戶是3歲2個月大。

private function calculateAge(dob:Date):String {   
    var now:Date = new Date(); 

    var ageDays:int = 0; 
    var ageYears:int = 0; 
    var ageRmdr:int = 0; 

    var diff:Number = now.getTime()-dob.getTime(); 
    ageDays = diff/86400000; 
    ageYears = Math.floor(ageDays/365.24); 
    ageRmdr = Math.floor((ageDays - (ageYears*365.24))/30.4375); 

    if (ageRmdr == 12) { 
     ageRmdr = 11; 
    } 

    return ageYears + " years " + ageRmdr + " months"; 
} 
3
var userDOB : Date = new Date(year,month-1,day); 
var today : Date = new Date(); 

var diff : Date = new Date(); 
diff.setTime(today.getTime() - userDOB.getTime()); 

var userAge : int = diff.getFullYear() - 1970; 
1

這裏是一個班輪:

int(now.getFullYear() - dob.getFullYear() + (now.getMonth() - dob.getMonth())*.01 + (now.getDate() - dob.getDate())*.0001); 
1

,我發現這裏的頂部回答幾個問題。我在這裏用了幾個答案來拼湊一些準確的東西(對我來說,無論如何,也希望你也是這樣!)

private function getYearsOld(dob:Date):uint 
{ 
    var now:Date = new Date(); 
    var age:Date = new Date(now.getTime() - dob.getTime()); 
    var yearsOld:uint = age.getFullYear() - 1970; 
    return yearsOld; 
}