Posted By

bsuichies on 03/14/12


Tagged

function AGE calculate


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

danfolt


Calculate age


 / Published in: PHP
 

Calculate age in years based on a timestamp and a reference timestamp (which defaults to the current time when left empty)

  1. /**
  2.  * Calculate age in years based on timestamp and reference timestamp
  3.  * If the reference $now is set to 0, then current time is used
  4.  *
  5.  * @param int $timestamp
  6.  * @param int $now
  7.  * @return int
  8.  */
  9. function calculateAge($timestamp = 0, $now = 0) {
  10. # default to current time when $now not given
  11. if ($now == 0)
  12. $now = time();
  13.  
  14. # calculate differences between timestamp and current Y/m/d
  15. $yearDiff = date("Y", $now) - date("Y", $timestamp);
  16. $monthDiff = date("m", $now) - date("m", $timestamp);
  17. $dayDiff = date("d", $now) - date("d", $timestamp);
  18.  
  19. # check if we already had our birthday
  20. if ($monthDiff < 0)
  21. $yearDiff--;
  22. elseif (($monthDiff == 0) && ($dayDiff < 0))
  23. $yearDiff--;
  24.  
  25. # set the result: age in years
  26. $result = intval($yearDiff);
  27.  
  28. # deliver the result
  29. return $result;
  30. }

Report this snippet  

You need to login to post a comment.