php 从日期字符串获取微时间

2022-08-31 01:14:12

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

例:

$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()


答案 1

尝试使用DateTime代替。

这需要一些解决方法,因为(由 )不计算微秒,因此您需要手动执行此操作DateIntervalDateTime::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);
}

答案 2

基于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;

完整说明:

  • 我们将两个日期之间的签名微秒差存储在中,并通过除以1000 * 1000来转换结果(以秒为单位)$uDiff
  • 操作数的顺序很重要,并且必须与$timePassed操作中的顺序相同。$uDiff
  • 我们计算两个日期之间的Unix时间戳(以整秒为单位)差值,并将微秒差值相加以获得所需的结果
  • 使用 DateTime::getTimestamp() 即使差值大于 60 秒,也会给出正确的答案

推荐