views:

246

answers:

2

I'm trying to calculate age in flex. I've found this previous question http://stackoverflow.com/questions/41763/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!

A: 

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"; 
}
Richard Harrison
A: 

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