好吧,一个非常简单的问题,但我太厚了,无法弄明白.我希望两次得到区别.例如,"1:07"(1分7秒)和"3:01"(3分1秒).它只会是几分钟和几秒钟.我一直试图利用这个:
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;
}
Run Code Online (Sandbox Code Playgroud)
但我认为我的方向是错误的?
感谢您的任何帮助.
我试过这个:echo timeDiff('1:07','2:30');
我得到了这个输出"4980"
以上是什么?是秒吗?我不知道怎么把它变成"1:23",这就是区别.
谢谢大家,我从这一个线程中学到了很多东西,特别是.保罗的.它运作得很好,我喜欢防守!
Pau*_*xon 13
你不能使用strtotime,因为它会将MM:SS解释为HH:MM - 这就是为什么你得到的值高于预期.
你可以简单地在你的MM:SS值前加上'00:',使它们看起来像HH:MM:SS.
但请注意,strtotime,如果只给出HH:MM:SS,将给出今天的时间戳,这对于一次性代码来说很好.不要将这种技术用于任何重要的事情,考虑一下如果你的两个叫strtotime的呼叫跨越午夜会发生什么!
或者,像这样的东西会将MM:SS值转换为可以进行算术运算的时间戳
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;
}
}
Run Code Online (Sandbox Code Playgroud)
它比使用爆炸更具防御性,但显示了另一种方法!
小智 6
这应该给你两秒之间的差异.
$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;
Run Code Online (Sandbox Code Playgroud)