php从日期字符串中获取microtime

时间:2012-04-23 22:23:42

标签: php strtotime microtime

我想在两个日期时间字符串(包括毫秒)之间传递时间

示例:

$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()不允许你给它一个日期字符串...是否有一个替代函数来计算它,或者我将不得不做一些字符串解析来提取秒和毫秒并减去? / p>

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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时间戳(以秒为单位)差异,我们添加微秒差异以获得想要的结果
  • 即使差异大于60秒,使用DateTime::getTimestamp()也会给出正确答案