What is the best way to calculate Age using Flex? [closed]

可紊 提交于 2019-12-20 06:06:16

问题


What is the best way to calculate Age using Flex?


回答1:


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.




回答2:


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;



回答3:


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



回答4:


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



回答5:


Here's a one-liner:

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



回答6:


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


来源:https://stackoverflow.com/questions/41763/what-is-the-best-way-to-calculate-age-using-flex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!