Formatting date difference in human-friendly terms I've written a function to take the difference between two dates and display it in a particular format. I've used a lot of if-else statements, which seems a little messy. Is there a way to shorten this up? Would using the ternary operator make sense?

$date1 = '2018-04-30 10:36:29';
$date2 = '2018-04-30 10:35:29';

echo dateDiff($date1, $date2);

function dateDiff($date1, $date2)
{
    $date_1 = new DateTime($date1);
    $date_2 = new DateTime($date2);

    $diff = $date_1-&gt;diff($date_2);

    if($diff-&gt;days &gt; 365){
      return $date_1-&gt;format('Y-m-d');
    }

    elseif($diff-&gt;days &lt; 366 AND $diff-&gt;days &gt; 7){
      return $date_1-&gt;format('M d');
    }

    elseif($diff-&gt;days &gt; 2 AND $diff-&gt;days &lt; 8){
      return $date_1-&gt;format('L - H:i');
    }

    elseif($diff-&gt;days == 2) return "Yesterday ".$date_1-&gt;format('H:i');

    elseif($diff-&gt;days &lt; 2 AND $diff-&gt;days &gt; 0 OR $diff-&gt;days == 0 AND $diff-&gt;h &gt; 1) return $date_1-&gt;format('H:i');

    elseif($diff-&gt;days == 0 AND $diff-&gt;h &lt; 1 AND $diff-&gt;i &gt;= 1) return $diff-&gt;i." min ago";

    elseif($diff-&gt;days == 0 AND $diff-&gt;h &lt; 1 AND $diff-&gt;i &lt; 1) return "just now";

    else return $error = "Error!";

}
Chained ternary expressions in PHP are a major pain in the ass — don't use them!

You have a lot of tests that are redundant, since earlier tests will have already eliminated longer periods.  The error case at the end also seems pointless.

Use consistent indentation and braces for readability and safety — please don't skimp.

function dateDiff($date1, $date2)
{
    $date_1 = new DateTime($date1);
    $date_2 = new DateTime($date2);
    $diff = $date_1-&gt;diff($date_2);

    if ($diff-&gt;days &gt; 365) {
        return $date_1-&gt;format('Y-m-d');
    } elseif ($diff-&gt;days &gt; 7) {
        return $date_1-&gt;format('M d');
    } elseif ($diff-&gt;days &gt; 2) {
        return $date_1-&gt;format('L - H:i');
    } elseif ($diff-&gt;days == 2) {
        return "Yesterday ".$date_1-&gt;format('H:i');
    } elseif ($diff-&gt;days &gt; 0 OR $diff-&gt;h &gt; 1) {
        return $date_1-&gt;format('H:i');
    } elseif ($diff-&gt;i &gt;= 1) {
        return $diff-&gt;i." min ago";
    } else {
        return "Just now";
    }
}


Be sure to use consistent capitalization for "yesterday" and "just now".