I'm trying to calculate age in flex. I've found this previous question What is the best way to calculate Age using Flex?
I'm sort of leaning towards this
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"; 开发者_运维问答}
but I don't understand 100% whats going on.
How do I go Implementing this into my code say if the date was 12/23/1990?
Also How would I go about modifying this code to calculate the age if two dates are provided instead of using the current date? eg. 12/23/1990 - 10/15/1999
Thanks!
Date.getTime() returns the number of milliseconds since Jan 1, 1970, so diff is the number of milliseconds between the two dates. The code divides by 86400000 because that is the number of milliseconds per day. The rest should be obvious.
To modify the function to allow two dates to be entered, you could change the function like this:
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";
}
I would imagine that changing as follows would work:
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";
}
精彩评论