0

I have following code to get time diffrence

$t1 = "1515397514"; //a timestamp value
$t2 = "1515402944"; //a timestamp value

echo date("M d Y H:i:s",$t1)."<br />"; //Jan 08 2018 07:45:14
echo date("M d Y H:i:s",$t2)."<br />"; //Jan 08 2018 09:15:44

echo human_time_diff( $t1, $t2); // 2 hours

it returning 2 hours but I need 1:30 the exact time difference of 07:45 - 09:15

Any helps?

2

human_time_diff() only returns a single {number} {unit} string back. It rounds to nearest whole unit, instead of breaking down the difference precisely.

To get an exact duration difference, you'll need to use your own function. As this is a popular need in PHP, there's lots of solutions online - here's a clever one I found:

$t1 = "Jan 08 2018 07:45:14";
$t2 = "Jan 08 2018 09:15:44";

echo time_elapsed_string($t1,$t2);

function time_elapsed_string($datetime,$datetime2, $full = true) {
    $now = new DateTime($datetime2);
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}

Which'll give you:

1 hour, 30 minutes, 30 seconds ago
  • Thanks David, Its worked well, this is what I was looking for, but I thought any parameter should be passed to human_time_diff, anyway its working well... – Riyas Muhammed Jan 8 '18 at 19:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.