Home > Backend Development > PHP Tutorial > How to Reliably Calculate Age from a DD/MM/YYYY Date of Birth in PHP?

How to Reliably Calculate Age from a DD/MM/YYYY Date of Birth in PHP?

Patricia Arquette
Release: 2024-12-05 06:48:14
Original
705 people have browsed it

How to Reliably Calculate Age from a DD/MM/YYYY Date of Birth in PHP?

PHP: Calculating Age from DOB in "dd/mm/yyyy" Format

Calculating the age of a person from their date of birth can be a challenging task, especially when dealing with large quantities of data. This question focuses on a specific challenge encountered with a previous method that utilized a while loop to increment the age until the current date was reached.

One alternative method suggested in the question involves using the strtotime() and floor() functions to calculate the difference between the current time and the date of birth. However, as noted, this method also faces limitations.

A Reliable Solution

A more reliable approach is to calculate the age based on the day and month of the date of birth and the current date. Here's a revised PHP function that addresses the issues encountered:

<?php
function calculateAge($birthDate) {
  $birthDate = explode("/", $birthDate);
  $age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md")
    ? ((date("Y") - $birthDate[2]) - 1)
    : (date("Y") - $birthDate[2]));
  return $age;
}

$dob = "14/09/1986";
$age = calculateAge($dob);
echo "Age: ".$age;
?>
Copy after login

Implementation Details

  • The calculateAge() function takes a string representing the date of birth in "dd/mm/yyyy" format as input.
  • It splits the string into an array of date components (month, day, year).
  • It calculates the difference between the current time and the date of birth using the mktime() function.
  • It compares the month and day of the birthdate with the current month and day to determine if there has been a birthday this year.
  • Based on this comparison, it adjusts the age calculation accordingly.

This approach provides a precise and efficient way to calculate the age of an individual, regardless of the number of DOBs being processed.

The above is the detailed content of How to Reliably Calculate Age from a DD/MM/YYYY Date of Birth in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template