16

我试图让两个日期时间字符串之间传递的时间(包括毫秒)

例子:

$pageTime = strtotime("2012-04-23T16:08:14.9-05:00");
$rowTime = strtotime("2012-04-23T16:08:16.1-05:00");
$timePassed = $rowTime - $pageTime;
echo $timePassed . "<br/><br/>";

我希望看到回显的是“1.2”,但strtotime()忽略了字符串的毫秒部分。另外,显然microtime()不允许你给它一个日期字符串......是否有计算这个的替代函数,或者我将不得不做一些字符串解析来提取秒和毫秒并减去?

4

2 回答 2

13

改用DateTime试试。

这需要一些解决方法,因为DateInterval(由 返回DateTime::diff())不计算微秒,因此您需要手动执行此操作

$pageTime = new DateTime("2012-04-23T16:08:14.1 - 5 hours");
$rowTime  = new DateTime("2012-04-23T16:08:16.9 - 5 hours");

// the difference through one million to get micro seconds
$uDiff = abs($pageTime->format('u')-$rowTime->format('u')) / (1000 * 1000);

$diff = $pageTime->diff($rowTime);

echo $diff->format('%s')-$uDiff;

我总是推荐DateTime因为它的灵活性,你应该研究一下

编辑

为了向后兼容 PHP 5.2,它采用与毫秒相同的方法:

$pageTime = new DateTime("2012-04-23T16:08:14.1 - 5 hours");
$rowTime  = new DateTime("2012-04-23T16:08:16.9 - 5 hours");

// the difference through one million to get micro seconds
$uDiff = abs($pageTime->format('u')-$rowTime->format('u')) / (1000 * 1000);


$pageTimeSeconds = $pageTime->format('s');
$rowTimeSeconds  = $rowTime->format('s');

if ($pageTimeSeconds + $rowTimeSeconds > 60) {
  $sDiff = ($rowTimeSeconds + $pageTimeSeconds)-60;
} else {
  $sDiff = $pageTimeSeconds - $rowTimeSeconds;
}


if ($sDiff < 0) {
  echo abs($sDiff) + $uDiff;
} else {
  // for the edge(?) case if $dt2 was smaller than $dt
  echo abs($sDiff - $uDiff);
}
于 2012-04-23T22:29:23.540 回答
0

基于 Dan Lee 的回答,这是一个通用的解决方案:

$pageTime = new DateTime("2012-04-23T16:08:14.9-05:00");
$rowTime  = new DateTime("2012-04-23T16:08:16.1-05:00");

$uDiff = ($rowTime->format('u') - $pageTime->format('u')) / (1000 * 1000);

$timePassed = $rowTime->getTimestamp() - $pageTime->getTimestamp() + $uDiff;

完整解释:

  • 我们将两个日期之间的有符号微秒差存储在中$uDiff,并将结果除以 1000 * 1000 以秒为单位进行转换
  • 操作数的顺序$uDiff很重要,并且必须与 $timePassed 操作中的顺序相同。
  • 我们计算两个日期之间的 Unix 时间戳(以整秒为单位)差异,并添加微秒差异以获得想要的结果
  • DateTime::getTimestamp()即使差异大于 60 秒,使用也会给出正确答案
于 2016-07-12T20:04:19.640 回答