Calculate Elapsed Time Between Two Dates in PHP

Posted on January 30, 2019 at 10:54 pm

This function is used to calculate elapsed time between two dates:

function formatDateDiff($start, $end=null, $ago=" ago", $left=" left") {
    if(!($start instanceof DateTime)) {
        $start = new DateTime($start);
    }
 
    if($end === null) {
        $end = new DateTime();
    }
 
    if(!($end instanceof DateTime)) {
        $end = new DateTime($start);
    }
 
    $interval = $end->diff($start);
 
	$elapsedtype = ($interval->invert == 0) ? $ago : $left;
 
	// Adds plurals
    $doPlural = function($nb,$str){return $nb>1?$str.'s':$str;}; // adds plurals
 
    $format = array();
    if($interval->y !== 0) {
        $format[] = "%y ".$doPlural($interval->y, "year");
    }
    if($interval->m !== 0) {
        $format[] = "%m ".$doPlural($interval->m, "month");
    }
    if($interval->d !== 0) {
        $format[] = "%d ".$doPlural($interval->d, "day");
    }
    if($interval->h !== 0) {
        $format[] = "%h ".$doPlural($interval->h, "hour");
    }
    if($interval->i !== 0) {
        $format[] = "%i ".$doPlural($interval->i, "minute");
    }
    if($interval->s !== 0) {
        if(!count($format)) {
            return "less than a minute ago";
        } else {
            $format[] = "%s ".$doPlural($interval->s, "second");
        }
    }
 
    // We use the two biggest parts
    if(count($format) > 1) {
        $format = array_shift($format)." and ".array_shift($format);
    } else {
        $format = array_pop($format);
    }
 
    // Append 'ago ' or ' left'
    return $interval->format($format).$elapsedtype;
}

Reference:

http://php.net/manual/en/dateinterval.format.php#96768

I modified the function by adding the $elapsedtype.

Now the function shows “ago” or “left”, example:

$today      = new DateTime(date("Y-m-d H:i:s", time()));
$tomorrow   = new DateTime(date("Y-m-d H:i:s", strtotime("-13 minutes")));
 
print_r(formatDateDiff($today, $tomorrow)); // Outputs 13 minutes ago
 
$today      = new DateTime(date("Y-m-d H:i:s", time()));
$tomorrow   = new DateTime(date("Y-m-d H:i:s", strtotime("+13 months")));
 
print_r(formatDateDiff($today, $tomorrow)); // Outputs 1 year and 1 month left

Receive updates via email

Other Posts

Updated Posts