PHP 从日期字符串中获取微时间


php get microtime from date string

我正在尝试获取两个日期时间字符串之间经过的时间(包括毫秒)

例:

$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()不让你给它一个日期字符串......是否有用于计算此值的替代函数,或者我是否必须进行一些字符串解析来提取秒和毫秒并减去?

试试日期时间。

这需要一些解决方法,因为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);
}

基于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 秒也会给出正确答案