2010-03-03 246 views
1

我正在嘗試計算flex中的年齡。我發現這個先前的問題What is the best way to calculate Age using Flex?Flex中的年齡計算

我對這個

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"; } 

有點傾斜,但什麼事情我不明白100%。

我該如何去實現這個到我的代碼說如果日期是12/23/1990?

另外如果提供兩個日期而不是使用當前日期,我該如何修改此代碼來計算年齡?例如。 12/23/1990 - 10/15/1999

謝謝!

回答

0

Date.getTime()自1970年1月1日的毫秒數,所以差異是兩個日期之間的毫秒數。代碼除以86400000,因爲那是每天的毫秒數。其餘的應該是顯而易見的。

要修改的功能,允許輸入兩個日期,你可以改變這樣的功能:


private function calculateAge(dob:Date, endDate:Date):String {   
    var ageDays:int = 0; 
    var ageYears:int = 0; 
    var ageRmdr:int = 0; 
    var diff:Number = endDate.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"; 
} 
0

我會想象,改變如下會的工作:

private function calculateAge(dob:Date, startfrom:Date):String {   

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

var diff:Number = startfrom.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"; 
}