0

What is the best way to calculate Age using Flex?

Christophe Herreman
  • 15,895
  • 9
  • 58
  • 86
Richard Braxton
  • 165
  • 2
  • 8

6 Answers6

13

I found an answer at the bottom of this page in comments section (which is now offline).

jpwrunyan said on Apr 30, 2007 at 10:10 PM :

By the way, here is how to calculate age in years (only) from DOB without needing to account for leap years:

With a slight correction by Fine-Wei Lin, the code reads

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

This handles most situations where you need to calculate age.

Community
  • 1
  • 1
Richard Braxton
  • 165
  • 2
  • 8
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;
grapefrukt
  • 27,016
  • 6
  • 49
  • 73
1

Here's a one-liner:

int( now.getFullYear() - dob.getFullYear() + (now.getMonth() - dob.getMonth())*.01 + (now.getDate() - dob.getDate())*.0001 );
datico
  • 330
  • 2
  • 5
1

I found a few problems with the top answer here. I used a couple of answers here to cobble together something which was accurate (for me anyway, hope for you too!)

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;
}
jowie
  • 8,028
  • 8
  • 55
  • 94
1

You could also do it roughly the same as discussed here: (translated to AS3)

var age:int = (new Date()).fullYear - bDay.fullYear;
if ((new Date()) < (new Date((bDay.fullYear + age), bDay.month, bDay.date))) age--;
Community
  • 1
  • 1
Raleigh Buckner
  • 8,343
  • 2
  • 31
  • 38
1

Here is a little more complex calculation, this calculates age in years and months. Example: User is 3 years 2 months old.

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";
}
Matt MacLean
  • 19,410
  • 7
  • 50
  • 53