How to Calculate Age in PHP
Posted on: March 02, 2021 by Ariessa Norramli
In this article, you will learn how to calculate age based on birthdate in PHP.
Let’s say you have 2 string variables containing date of birth and current date.
$birthDate = "17-10-1998";
$currentDate = date("d-m-Y");
Calculate Age
In order to calculate age based on birthdate, you can use the date_diff()
method and date_create()
method.
$birthDate = "17-10-1998";
$currentDate = date("d-m-Y");
$age = date_diff(date_create($birthDate), date_create($currentDate));
echo "Current age is ".$age->format("%y");
// Current age is 22
Note: The date_diff()
method functions by calculating the mathematical difference of two supplied dates. The date_create()
method functions by creating a DateTime object from a supplied string.
Share on social media
//