从PHP中的DateTime添加时间

时间:2017-07-02 21:00:06

标签: php

我会尝试解释我的问题。我是PHP的初学者,需要帮助操作日期/时间。

所以这是我的情况。

我以这种格式从数据库中获取日期/时间值:07/02/2017 11:00 pm

首先,我需要计算两个日期和输出持续时间之间的差异。

然后加上持续时间和输出总时间。

因为我现在正在研究,所以代码非常脏。我也遇到了一个问题,即DateTime没有带点数。据我所知,我需要将天数转换为数小时并将其添加。

任何更有经验的人都可以理解这一点吗?

$total_time = new DateTime('00:00');

$start_date = new DateTime('2017-05-01 12:20 PM');
$end_date = new DateTime('2017-05-01 12:30 PM');

$interval = $start_date->diff($end_date);

$total_days = $interval->days;
$hours      = $interval->h;

if ($total_days !== FALSE) {
    $hours += 24 * $total_days;
}
$minutes    = $interval->i;


$total_time ->add($interval);

echo $hours .'hours ' . $minutes . 'minutes';

echo $total_time->format('h:i'); ?>

1 个答案:

答案 0 :(得分:0)

您可以将DateInterval添加到DateTime。

您可以查看http://php.net/manual/en/datetime.add.php

查看您的代码:

$total_hours = 0;
$total_minutes = 0;
//must be initialized outside of the while loop

$start_date = new DateTime('2017-05-01 12:20 PM');
$end_date = new DateTime('2017-05-01 12:30 PM');

$interval = $start_date->diff($end_date);

$hours = $interval->h + 24*$interval->d; /*there is no need to check
if you have total days, since 0 days would still work as expected */

$minutes = $interval->i;

echo 'Duration: '.$hours.' hours '.$minutes.' minutes';

$total_hours += $hours;

if(($total_minutes += $minutes) >= 60) {
    $total_hours += 1;
    $total_minutes -= 60;
}

//after the end of the while loop

echo 'Total time:'.$total_hours.':'.$total_minutes;

现在我不明白总时间的预期输出是多少,如果你能详细说明什么是无效的,那将更容易提供帮助