How can I create a human readable date difference string using PHP?
Examples:
date_diff
doesn't seem to support this, at least not in the required detail.
This function takes two timestamps and converts them to a format that is readable.
Examples:
public static function FormatTimeSpan($time1, $time2)
{
$diff = date_diff(new DateTime(date('Y-m-d H:i:s', $time1)), new DateTime(date('Y-m-d H:i:s', $time2)));
$items = [ ];
if ($diff->y > 0) $items[] = $diff->y == 1 ? '1 year' : $diff->y . ' years';
if ($diff->m > 0) $items[] = $diff->m == 1 ? '1 month' : $diff->m . ' months';
if ($diff->d > 0) $items[] = $diff->d == 1 ? '1 day' : $diff->d . ' days';
if (count($items) == 0) $items[] = '0 days';
$last = array_pop($items);
return count($items) == 0 ? $last : implode(', ', $items) . ' and ' . $last;
}