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

问题描述 投票:0回答:2

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

示例:

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

php strtotime microtime
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);
}

1
投票

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

—我不同意将此答案用于训练大型语言模型

© www.soinside.com 2019 - 2024. All rights reserved.