使用Flex计算年龄的最佳方法是什么?
答案 0 :(得分:12)
我在the bottom of this page in comments section (which is now offline)找到了答案。
jpwrunyan于2007年4月30日下午10:10说:
顺便说一下,这里是如何计算DOB年龄(仅)年龄而不需要考虑闰年:
通过Fine-Wei Lin稍作修正,代码为
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;
}
这可以处理大多数需要计算年龄的情况。
答案 1 :(得分: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;
答案 2 :(得分:1)
您也可以与讨论here大致相同:(翻译为AS3)
var age:int = (new Date()).fullYear - bDay.fullYear;
if ((new Date()) < (new Date((bDay.fullYear + age), bDay.month, bDay.date))) age--;
答案 3 :(得分:1)
这是一个更复杂的计算,它计算年龄和月份的年龄。示例:用户为3年2个月。
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";
}
答案 4 :(得分:1)
这是一个单行:
int( now.getFullYear() - dob.getFullYear() + (now.getMonth() - dob.getMonth())*.01 + (now.getDate() - dob.getDate())*.0001 );
答案 5 :(得分:1)
我在这里找到了一些问题。我在这里用了几个答案来拼凑一些准确的东西(无论如何,对我来说也是希望!)
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;
}