Find out current age

Discussion in 'PHP' started by MajHate, Mar 22, 2009.

  1. #1
    Hello,

    I have birth dates entered in my database entered in the form of numerals. So someone born on January 20th, 1990 would be 1 20 1990. I am trying to create a script so it will tell you your current age. I tried just using the current year, 2009 subtracted by there year of birth, but it is not accurate. I have to use the months and days as well, not just the year. Does anyone know how to do this?

    Thank You,
    Jason
     
    MajHate, Mar 22, 2009 IP
  2. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #2
    < ?php $dob = mktime(0, 0, 0, 10, 10, 1950); echo round(((time() - $dob) / 31557600), 0); ?>

    This is the code I use on a page of mine to display my age in years - if you exchange the mktime() with the values from your database, it should work (you might have to pull it with some type of formatting, but it should work).

    Hope it gets you started, at least.

    (And no, that's not my birthdate ;) )
     
    PoPSiCLe, Mar 22, 2009 IP
  3. ads2help

    ads2help Peon

    Messages:
    2,142
    Likes Received:
    67
    Best Answers:
    1
    Trophy Points:
    0
    #3
    PHP won't know its January if you strtotime like this:
    $time = strtotime("1 20 1990");

    So, (might not be the best way but it works)

    
    $dob = explode(" ","1 20 1990");
    $dob_stamp = mktime(0, 0, 0, $dob[0], $dob[1], $dob[2]);
    $one_year_in_secs = 60*60*24*365;
    $age = floor($dob_stamp/$one_year_in_secs);
    echo $age;
    
    PHP:
    I use floor() instead of round()

    - ads2help
     
    ads2help, Mar 22, 2009 IP
  4. MajHate

    MajHate Member

    Messages:
    48
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #4
    I forgot to say that I have the day, month and year in 3 different fields, they are not all together. How do I edit the script to make it for like that?
     
    MajHate, Mar 22, 2009 IP
  5. ads2help

    ads2help Peon

    Messages:
    2,142
    Likes Received:
    67
    Best Answers:
    1
    Trophy Points:
    0
    #5
    After explode() using blankspace " ",
    - $dob[0] carries the month
    - $dob[1] carries the day
    - $dob[2] carries the year

    So,
    
    $dob_stamp = mktime(0, 0, 0, $yoursql_month, $yoursql_day, $yoursql_year);
    $one_year_in_secs = 60*60*24*365;
    $age = floor($dob_stamp/$one_year_in_secs);
    echo $age;
    
    PHP:
    Just replace $yoursql_month, $yoursql_day, $yoursql_year with the result from sql.

    - ads2help
     
    ads2help, Mar 22, 2009 IP