w3resource

PHP Date Exercises : Calculate the current age of a person


18. Calculate Current Age of a Person

Write a PHP script to calculate the current age of a person.

Sample date of birth : 11.4.1987

Sample Solution:

PHP Code:

<?php
$bday = new DateTime('11.4.1987'); // Creating a DateTime object representing your date of birth.
$today = new Datetime(date('m.d.y')); // Creating a DateTime object representing today's date.
$diff = $today->diff($bday); // Calculating the difference between your date of birth and today's date.
printf(' Your age : %d years, %d month, %d days', $diff->y, $diff->m, $diff->d); // Displaying your age in years, months, and days.
printf("\n"); // Adding a new line for formatting.
?>

Output:

 Your age : 30 years, 3 month, 0 days

N.B.: The result may varry for your system date and time.

Explanation:

In the exercise above,

  • $bday = new DateTime('11.4.1987');: Creates a "DateTime" object representing your date of birth. The date is provided in the format 'month.day.year'.
  • $today = new Datetime(date('m.d.y'));: Create a "DateTime" object representing today's date using the date function to get the current date in the format 'month.day.year'.
  • $diff = $today->diff($bday);: Calculates the difference between your date of birth and today's date using the "diff()" method of the "DateTime" object. This returns a DateInterval object representing the difference.
  • printf(' Your age : %d years, %d month, %d days', $diff->y, $diff->m, $diff->d);: Using "printf()" to format and display your age. '%d' is a placeholder for integers, and we pass the years, months, and days from the "DateInterval" object as arguments.
  • printf("\n");: Adding a newline character for formatting.

Flowchart :

Flowchart: Calculate the current age of a person

For more Practice: Solve these Related Problems:

  • Write a PHP script that calculates a person's age in years, months, and days based on their birthdate and today's date.
  • Write a PHP function that takes a birthdate string and returns the full age breakdown including time in hours and minutes.
  • Write a PHP program to compare two birthdates and output whose age is greater along with the age difference.
  • Write a PHP script to compute the age of a person using DateTime objects and display it in a well-formatted paragraph.

Go to:


PREV : Start and End Date of Week by Week Number.
NEXT : Calculate Weeks Between Two Dates.

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.