1

For example if I was given the string "01/01/1980". How could I then get the current date, then figure out how old someone is, and then just return how many years old they are?

I saw a topic on this in C++ but i'm not to familiar with it, anyone know how this would be done in AS3?

edit: I think what i'm having the hardest time with is how I would break down the original brithday string i'm starting with into month, day, year vars

brybam
  • 5,009
  • 12
  • 51
  • 93

4 Answers4

3

Man, a lot of people here like convoluted complex code. Here's how you simplify it:

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

From the tests I've done, this is accurate 100% and I think should be the fastest you can make it since you're not doing any rounding or complex math, just conditionals.

J_A_X
  • 12,857
  • 1
  • 25
  • 31
  • @J_A_X. The core of the calculation is just one line in your example. In Neal's, it could be naturally written in four (first get the years difference, then substract another year if neccesary). But why getting a close approximate when you can get the correct result with just two more lines? Also, coercing to uint is not the wisest choice. Suppose you want to check if someone is above 18; if the given dob is in the future, you will not get a negative number (which will fail a simple `(if age >= 18)`) because of wrapping. Sure, you could validate, but not as simply and elegantly. – Juan Pablo Califano Mar 30 '11 at 02:06
  • ya, this is a good one. surprised I didn't see this on the one I linked to. @Juan Pablo - this will give you an accurate answer. Try to come up with 2 dates that make it fail (assuming you put your own date in 'today' i.e new Date(1988,02,02)) – Scott Mar 30 '11 at 02:16
  • 1
    @Scott. There are real-scenario dates that can make it fail (though as I mention and as J_A_X does too, most of the times, it just works). Most errors are appreciable on february, especially on leap years, given a big enough number of years of difference between the dates to make rounding errors accumulate: (flash style dates) `(2012,1,28) - (1972,1,28) = 40;` vs `(2012,1,28) - (1971,1,28) = 40;`; `(2012,1,28) - (1948,1,28) = 64;` vs `(2012,1,28) - (1949,1,28) = 62;`. I don't mean to be harsh, but this code is flawed, and getting it right is not that hard, either. – Juan Pablo Califano Mar 30 '11 at 03:01
  • The case that does make it fail is (2012,1,28) - (1949,1,28) = 62, which should be 63. Good point. – Scott Mar 30 '11 at 03:19
  • @Juan Pablo Califano You're right, I was in a bit of a hurry. After thinking about it last night, I've come up with a better solution which is 100% accurate and only takes 3 lines of code. – J_A_X Mar 30 '11 at 14:25
  • @J_A_X. Sorry. It's still wrong. Check it with today's date and 10 years of difference. `(2001,2,30) - (2011,2,30);`. Your code returns 9. I think you're off for one day now, and you could add another magic constant, but this isn't by any means simpler, clearer or more elegant than Neal's code (I mean, the core of the calculation, not the whole code). Plus, you'd need to add a condition anyway to deal with people born on 29 February (which is not dealt with in the other examples, either). – Juan Pablo Califano Mar 30 '11 at 14:41
  • @Juan, actually, today is the 3rd month, not the 2nd, so my code does work for that example, but now that I think about it, there's a 1/1460 chance of error (damn leap years). I've modified the code to include leap years. I also fail to see how this code is more complex than Neal's. – J_A_X Mar 30 '11 at 15:09
  • @J_A_X. I think the problem manifests itself on the year-change boundary, leap year or not. For instance: (2011,1,2) - (2010,1,2) should return 1, but returns 0. If you hack it adding a few hours to today's date, you might get it right (at least in this example). How many hours? Go figure, dayligh savings probably come into play here, which depend on locales (also, the way daylight savings are calculate may vary from one year to another, even in the same country). – Juan Pablo Califano Mar 30 '11 at 15:10
  • @J_A_X. Today is the 3rd month, but flash months are zero based, so the month value should be 2, not 3. – Juan Pablo Califano Mar 30 '11 at 15:12
  • @J_A_X. re: simplicity. To get your code working correctly, you'd have to make it more complex, to check some problematic conditions. So, it wouldn't be as simple as it was originally. You said yours was simpler than other people's convoluted code, which will no longer be true if you change it to get correct results. Neal's is straigh forward I think. That's how people calculate someone's age mentally, I guess. – Juan Pablo Califano Mar 30 '11 at 15:16
  • @J_A_X. I mentioned I was using flash style dates above, and I also haven't used quotes. But anyway, that's not important, whether we say (2011,2,30) or "03/30/2011", between that date and "03/30/2001", 10 years have passed, not 9. – Juan Pablo Califano Mar 30 '11 at 15:20
  • @Juan, have you even tried my code or just desperately trying to make me look wrong? I've created several test cases, all of which pass without a hitch. My current code gives me '10' for your example. I've tried with leap years as well with perfect results. Also, 'mental calculation' != programming. If you don't understand my code which is very clear to me (and I'm sure others), you can ignore it. – J_A_X Mar 30 '11 at 15:26
  • @J_A_X. Sorry, I was trying 2001,2,30 - 2011,2,30 with your 3rd revision, not the current one, my bad. I'm not trying to make you look wrong (desperately or otherwise). I was just pointing out a flaw, that you've now seem to have corrected. I understand your code, buy I think the other option is simpler as I mentioned. But anyway, if you like your code better, fine by me. – Juan Pablo Califano Mar 30 '11 at 15:39
  • The code (as of this comment) is now the same as this posting http://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c – Scott Mar 30 '11 at 20:38
  • I decided to just go with this one, and when floor it, it seems to work just like i need it to. Thanks a lot! – brybam Mar 30 '11 at 23:39
2

check out this link (GOOGLE IS YOUR FRIEND :-))

The code (direct copy from site):

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));
Naftali
  • 144,921
  • 39
  • 244
  • 303
  • 2
    +1 for simplest solution. The others just love to "simplicate" with needless divisions and multiplications. Sometimes an if is better. – bug-a-lot Mar 30 '11 at 08:59
  • 1
    can someone explain the `-1`? – Naftali Mar 30 '11 at 16:16
  • This is the solution I've always used in the past. I like it and it makes sense to someone reading the code. I do like some of the division methods as they are interesting ways of getting to the same answer. – Scott Mar 30 '11 at 20:40
  • @Neal you need to replace `getDay()` by `getDate()`. The former is the day of week. – Majid Laissi Apr 01 '13 at 22:57
0

Check out this question. It has a solution that is really slick.

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)
Community
  • 1
  • 1
Scott
  • 16,711
  • 14
  • 75
  • 120
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)
The_asMan
  • 6,364
  • 4
  • 23
  • 34