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.
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.
Thank you all, I learnt so much just from this one thread, esp. Paul's. It works very well and I like the defensiveness!
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;
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With