Search code examples
phpdatetimedatediff

How to output "X years, Y months and Z days" using date_diff?


How can I create a human readable date difference string using PHP?

Examples:

  • X day(s)
  • X month(s)
  • X day(s) and Y month(s)
  • X year(s), Y month(s) and Z day(s)

date_diff doesn't seem to support this, at least not in the required detail.


Solution

  • This function takes two timestamps and converts them to a format that is readable.

    • It returns only the parts (years/months/days) that are > 0
    • It considers singular and plural for year(s), month(s) and day(s)
    • It concatinates with "," and with "and", depending on how many items are displayed

    Examples:

    • 1 day ago
    • 3 days ago
    • 1 month and 3 days ago
    • 3 months and 1 day ago
    • 1 year and 5 days ago
    • 2 years, 10 months and 16 days ago
    • 2 years and 1 day ago

    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;
    }