如何在动作脚本3中将生日字符串转换为年龄?

时间:2011-03-29 22:30:23

标签: flex actionscript-3 string date-of-birth

例如,如果给我字符串“01/01/1980”。那我怎么能得到当前的日期,然后弄清楚有多大了,然后回到他们多少岁?

我在C ++中看到了一个关于这个的话题,但是我不熟悉它,有人知道如何在AS3中完成这个吗?

编辑:我认为我遇到的最困难的事情是我如何打破原来的生日字符串,我将开始进入月,日,年变量

4 个答案:

答案 0 :(得分:3)

男人,这里很多人都喜欢错综复杂的代码。以下是简化它的方法:

// Parse the date string     
var dob:Date = DateFormatter.parseDateString("03/30/2001");
// Get todays timestamp at 00:00:00
var today:Date = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate());
// Do the age differrence
var age:uint = today.getFullYear() - dob.getFullYear();
// Set DOB to this year
dob.setFullYear(today.getFullYear());
// Check to see if we haven't passed today's date
if(dob.getTime() < today.getTime()){ age--; }

从我所做的测试来看,这是100%准确的,我认为应该是你能做到的最快,因为你没有做任何舍入或复杂的数学,只是条件。

答案 1 :(得分:2)

查看此link GOOGLE是您的朋友: - )

代码(来自网站的直接复制):

function calculateAge(birthdate:Date):Number {
    var dtNow:Date = new Date();// gets current date
    var currentMonth:Number = dtNow.getMonth();
    var currentDay:Number = dtNow.getDay();
    var currentYear:Number = dtNow.getFullYear();

    var bdMonth:Number = birthdate.getMonth();
    var bdDay:Number = birthdate.getDay();
    var bdYear:Number = birthdate.getFullYear();

    // get the difference in years
    var years:Number = dtNow.getFullYear() - birthdate.getFullYear();
    // subtract another year if we're before the
    // birth day in the current year
    if (currentMonth < bdMonth || (currentMonth == bdMonth && currentDay < bdDay)) {
        years--;
    }
    return years;
}

function dateStringToObject(dateString):Date {
    var date_ar = dateString.split("/");
    return new Date(date_ar[2],date_ar[0] - 1,date_ar[1]);
}

var dateNow:Date = new Date();
var checkDate:String = "11/25/1976";
var dateBirthday:Date = dateStringToObject(checkDate);
trace("dateNow = "+dateNow);
trace("dateBirthday = "+dateBirthday);
trace("age = "+calculateAge(dateBirthday));

答案 2 :(得分:0)

查看此question。它有一个非常光滑的解决方案。

var today = new Date()
var birthday = new Date(1980, 00, 12)  //this is the birthday, you can have this be an input to a function as well if you wanted

var bigToday:int = today.getFullYear()*10000+(today.getMonth()+1)*100+today.getDate();
var bigBDay:int = birthday.getFullYear()*10000+(birthday.getMonth()+1)*100+birthday.getDate();

var diff:int = bigToday-bigBDay
var age:int = diff/10000

trace (age)

答案 3 :(得分:0)

var nowDate:Date = new Date( )
var bDate:Date = new Date( '01/01/1980' )
var age:Number = nowDate.getFullYear() - bDate.getFullYear()
if( nowDate.getUTCMonth()*100 + nowDate.getUTCDay() < bDate.getUTCMonth()*100 + bDate.getUTCDay()  ){
  --age
}
trace(age)