PHP DateTime 格式有效,但 DateInterval 格式无效

PHP DateTime formatting works but DateInterval formatting not working

我这里有一些 PHP 代码可以计算(并回显)持续时间。我有一个 if/else 选择如何计算持续时间。由于我进行计算的方式,在一种情况下输出的持续时间是 DateTime 对象,在另一种情况下它是 DateInterval 对象。两者的格式都是在 if/else 语句之外完成的。

计算工作正常,DateTime 对象的格式设置工作正常,但 DateInterval 对象的格式设置已关闭。它在输出时间内显示百分号(代码块末尾的示例)。

$time1 = new DateTime($row[0]); 
$time2 = new DateTime($row[1]);

if ($time1 > $time2) { 
    $twentyFourHours = new DateTime('240000');
    $difference = $time1->diff($twentyFourHours);
    $time2->add($difference);
    $duration = $time2; // this is a DateInterval object
}

else    {
$duration = $time2->diff($time1);  // This is a DateTime object
        }  

echo $duration->format('%H:%I');
echo '<br>';
echo $row['2'];
    }

下面是我得到的输出示例(每隔一个持续时间是带有百分号的 DateInterval 对象):

02:10
2016-06-16

%12:%0
2016-06-16

03:04
2016-06-17

%12:%0
2016-06-17

根据我在 DateInterval 格式化文档中了解到的情况,我正确地设置了两位数小时和两位数分钟的格式('%H:%I'),但输出似乎证明并非如此。我猜我忽略了一些愚蠢的事情,如果有人能指出我哪里出错了,我将不胜感激。

非常感谢!

我将其放入我的调试器并进行设置,使 $time1 比 $time2 大 2 小时 10 分钟,这看起来像您的第一个数据集并得到相同的错误。

在调试器中观察时,$duration 是 DateTime 对象而不是 Duration 对象。具体来说:

$duration = $time2; // this is a DateInterval object

$time2 是一个 DateTime 对象,所以 $duration 变成了一个 DateTime 对象,因此格式失败。

因此,在您的代码中:

   // find the duration since midnight
   $twentyFourHours = new DateTime('240000');
   $difference = $time1->diff($twentyFourHours);

   // add that difference to time2...hmmm
   $time2->add($difference);

   // copy time2 to duration, this will copy the $time2 DateTime object
   $duration = $time2; // this is a DateInterval object

看起来你正在获取 $time1 自午夜以来的持续时间,然后将其添加到 $time2,我想知道这是不是打字错误的地方,你打算在哪里做其他事情?希望对您有所帮助!

首先,它的工作原理与您的解释完全不同。为了检查你可以放置一个调试语句来输出对象的类型:

echo 'Type: ', get_class($duration), '<br>';

echo $duration->format('%H:%I');
echo '<br>';
echo $row['2'];

所以代码在 if-block returns DateTime 中,而代码在 else-block returns DateInterval.

您遇到问题的原因仅仅是 DateTime 和 DateInterval 具有不同的格式类型,DateInterval 确实需要使用 % 符号转义所有 formatting symbols while DateTime uses the same format styles as date function.

我看到了两种解决问题的方法:简单的一种是再引入一个存储必要格式的变量,并将其设置为 if 和 else 块中的相应值,另一种方法 - 重写代码以使 $持续时间变量在两种情况下具有相同的类型。