Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Calculate Age (See related posts)

With this function you can calculate the age of a person

Example:
echo "Age is: " . birthday ("1984-07-05");

Result will be (23 Feb 2005) = "Age is: 20"

<?php

  //calculate years of age (input string: YYYY-MM-DD)
  function birthday ($birthday){
    list($year,$month,$day) = explode("-",$birthday);
    $year_diff  = date("Y") - $year;
    $month_diff = date("m") - $month;
    $day_diff   = date("d") - $day;
    if ($day_diff < 0 || $month_diff < 0)
      $year_diff--;
    return $year_diff;
  }

?>

Comments on this post

flangemonkey posts on Jul 02, 2006 at 19:39
I think there is a little bug in the code in that the date checking is not thorough enough,

This extra line checks against the day only if the month matches and seems to always give the right answer,

 function birthday ($birthday)
  {
    list($year,$month,$day) = explode("-",$birthday);
    $year_diff  = date("Y") - $year;
    $month_diff = date("m") - $month;
    $day_diff   = date("d") - $day;
    if ($month_diff < 0) $year_diff--;
    elseif (($month_diff==0) && ($day_diff < 0)) $year_diff--;
    return $year_diff;
  }
    echo birthday("1980-07-02");
  }


also, as an aside, I am very new to php programming and have not posted before, so if I am stepping on peoples toes, I am very sorry :)
calamus77 posts on Apr 01, 2008 at 14:46
A much easier way to do this is just to compare date("md") against concatenated variables: ($month.$day):

function getAge( $p_strDate ) {
    list($Y,$m,$d)    = explode("-",$p_strDate);
    $years            = date("Y") - $Y;
    
    if( date("md") < $m.$d ) { $years--; }
    return $years;
}


I posted the above because many people don't like ?: syntax...but personally, I like getting things compact, so I would actually do the function like so:

function getAge( $p_strDate ) {
    list($Y,$m,$d)    = explode("-",$p_strDate);
    return( date("md") < $m.$d ? date("Y")-$Y-1 : date("Y")-$Y );
}

You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts