Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Work out duration between two times

Tags:

php

Ok, a really simple question but I am too thick to figure it out. I want to get the difference between two times. For example, "1:07" (1 minute and 7 seconds) and "3:01" (3 minutes and 1 second). It will only be ever minutes and seconds. I have been trying to make use of this:

function timeDiff($firstTime,$lastTime)
{

// convert to unix timestamps
$firstTime=strtotime($firstTime);
$lastTime=strtotime($lastTime);

// perform subtraction to get the difference (in seconds) between times
$timeDiff=$lastTime-$firstTime;

// return the difference
return $timeDiff;
}

But I think I am running in the wrong direction?

Thank you for any help.

EDIT

I tried this: echo timeDiff('1:07','2:30');

I got this output "4980"

What is the above? Is it seconds? I have no idea how to get it as "1:23" which is the difference.

EDIT 2

Thank you all, I learnt so much just from this one thread, esp. Paul's. It works very well and I like the defensiveness!

like image 505
Abs Avatar asked Feb 10 '09 21:02

Abs


2 Answers

This should give you the difference between the two times in seconds.

$firstTime = '1:07';
$secondTime = '3:01';

list($firstMinutes, $firstSeconds) = explode(':', $firstTime);
list($secondMinutes, $secondSeconds) = explode(':', $secondTime);

$firstSeconds += ($firstMinutes * 60);
$secondSeconds += ($secondMinutes * 60);
$difference = $secondSeconds - $firstSeconds;
like image 40
Anders S Avatar answered Sep 29 '22 09:09

Anders S


You can't use strtotime as it will interpret MM:SS as HH:MM - that's why you are getting higher values than expected.

You could simply prepend your MM:SS values with '00:' to make them look like HH:MM:SS.

Note however that strtotime, if just given HH:MM:SS, will give a timestamp for today, which is fine for throwaway code. Don't use that technique for anything important, consider what happens if your two calls to strtotime straddle midnight!

Alternatively, something like this will turn a MM:SS value into a timestamp you can do arithmetic on

function MinSecToSeconds($minsec)
{
    if (preg_match('/^(\d+):(\d+)$/', $minsec, $matches))
    {
        return $matches[1]*60 + $matches[2];
    }
    else
    {
        trigger_error("MinSecToSeconds: Bad time format $minsec", E_USER_ERROR);
        return 0;
    }
}

It's a little more defensive than using explode, but shows another approach!

like image 82
Paul Dixon Avatar answered Sep 29 '22 09:09

Paul Dixon