Calculating age with PHP


 
I've seen some posts that to calculate the age in years of a person there are problems if the date of birth is less than the year 1970 . That's because they spend time date UNIX and then make a subtraction and converted back to years.

The simplest thing I've seen is this feature that I leave here, you just grab first of months and days of the current date and birth and see if we have already passed or not yet. After years subtracts the part of both dates and finally adjusted.


function getAge($birthdate){
 $adjust = (date("md") >= date("md", strtotime($birthdate))) ? 0 : -1; // Si aún no hemos llegado al día y mes en este año restamos 1
 $years = date("Y") - date("Y", strtotime($birthdate)); // Calculamos el número de años
 return $years + $adjust; // Sumamos la diferencia de años más el ajuste
}

You can complicate making the input format can be configured but we have put in English format YYYY-MM-DD . The results are the following:

// Hoy es 2 de diciembre de 2014
echo getAge("1919-02-21"); // devuelve 95
 
echo getAge("1952-12-07"); // devuelve 61

I hope you serve.

Comments

Popular posts from this blog

Coronavirus symptoms: what are they and should I call the doctor?

6 Big Reasons to Learn Even a Little HTML & CSS

Ads