Last active
December 26, 2015 12:49
-
-
Save devoto13/7153686 to your computer and use it in GitHub Desktop.
PHP: format human age
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function formatAge($date, $point = null) { | |
$date = DateTime::createFromFormat('Y-m-d', $date); | |
$point = $point ? DateTime::createFromFormat('Y-m-d', $point) : new DateTime(); | |
$interval = $date->diff($point); | |
if ($interval->format('%r%a') <= 0) { | |
return false; | |
} | |
$years = $interval->format('%y'); | |
$months = $interval->format('%m'); | |
$days = $interval->format('%d'); | |
$parts = array(); | |
if ($years) { | |
$parts[] = $years; | |
$parts[] = ($years == 1 ? 'year' : 'years'); | |
if ($years < 3 && $months) { | |
$parts[] = 'and'; | |
$parts[] = $months; | |
$parts[] = ($months == 1 ? 'month' : 'months'); | |
} | |
} elseif ($months) { | |
$parts[] = $months; | |
$parts[] = ($months == 1 ? 'month' : 'months'); | |
} else { | |
$parts[] = $days; | |
$parts[] = ($days == 1 ? 'day' : 'days'); | |
} | |
return implode(' ', $parts); | |
} | |
$tests = array( | |
'2014-10-20' => false, | |
'2013-10-24' => '1 day', | |
'2013-10-20' => '5 days', | |
'2013-09-20' => '1 month', | |
'2013-06-20' => '4 months', | |
'2012-10-20' => '1 year', | |
'2012-03-20' => '1 year and 7 months', | |
'2011-10-20' => '2 years', | |
'2011-03-20' => '2 years and 7 months', | |
'2002-06-20' => '11 years' | |
); | |
foreach ($tests as $date => $correct) { | |
echo (formatAge($date, '2013-10-25') === $correct ? 'yes' : 'no ') . ' :: ' . formatAge($date, '2013-10-25') . "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment