Skip to content

Instantly share code, notes, and snippets.

@cp6
Created September 24, 2020 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cp6/a147d43d67c2e93b27cbc724b939d474 to your computer and use it in GitHub Desktop.
Save cp6/a147d43d67c2e93b27cbc724b939d474 to your computer and use it in GitHub Desktop.
Calculate age PHP function
<?php
function ageForDate(string $dob, string $date = 'today', bool $years_only = true): string
{
$from = new DateTime($dob);
$to = new DateTime($date);
$interval = $from->diff($to);
if ($years_only) {
return $from->diff($to)->y;//years
} else {
return $from->diff($to)->y . '.' . $from->diff($to)->m;//years.months
}
}
echo ageForDate('1985-04-28', 'today', false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment