How to Calculate Age in PHP

How to Calculate Age in PHP

In this article we will check how to calculate age in PHP

How to Calculate Age in PHP

In various application, we may have to calculate the current age from the date of birth. As we know there are several ways to do that. We will go one by one. You are free to choose which ones suits you the most.

How to Calculate Age in PHP

Method 1: Using DateTimeZone

[php]

$timezone = new DateTimeZone(‘America/Detroit’);
$age = DateTime::createFromFormat(‘d/m/Y’, ’06/07/1991′, $timezone)
->diff(new DateTime(‘now’, $timezone))
->y;

[/php]

 

Method 2: Use Carbon Library

Carbon is a PHP Date time Library which contains many useful methods to do date time related tasks. Carbon is heavily used in Laravel framework

[php]
function calculate_current_age($date) {
$date = new \Carbon\Carbon($date);
return (int) $date->diffInYears();
}
[/php]

or

[php]
$current_age = (new \Carbon\Carbon($date))->current_age ;
[/php]

 

These are some simple ways we can calculate current age of a person from Date of Birth.

Editorial Staff

A Learner and trying to share what I learned!