PHP-两次相加(HH:MM:SS)

时间:2018-11-07 13:31:19

标签: php

我有4个约会时间

   datatime1= 2018-10-01 13:00:00
   datatime2= 2018-10-01 13:59:00
   datatime3= 2018-10-01 14:29:00
   datatime4= 2018-10-01 15:29:00

所以我需要得到这个结果

  

PART1:datatime [2] -datatime [1] = 0:59:0

     

PART2:datatime [3] -datatime [2] = 0:30:0

     

PART3:datatime [4] -datatime [3] = 1:0:0

     

PART4:PART1 + PART3 = 1:59:0

Idk,如果这是正确的方法,但我可以得到 Part1,Part2 Part3 ,但我不知道如何获得 PART4

的结果
 $time1 = new DateTime('2018-10-01 13:00:00');
 $time2 = new DateTime('2018-10-01 13:59:00');
 $time3 = new DateTime('2018-10-01 14:29:00');
 $time4 = new DateTime('2018-10-01 15:29:00');


$part1= date_diff($time2,$time1)->format('%h:%i:%s');
$part2= date_diff($time3,$time2)->format('%h:%i:%s');
$part3= date_diff($time4,$time3)->format('%h:%i:%s');

2 个答案:

答案 0 :(得分:2)

我认为您的示例是错误的,因为part1 + part2将导致1:29而不是1:59。

解释可以在代码中作为注释找到。

<?php

 $time1 = new DateTime('2018-10-01 13:00:00');
 $time2 = new DateTime('2018-10-01 13:59:00');
 $time3 = new DateTime('2018-10-01 14:29:00');
 $time4 = new DateTime('2018-10-01 15:29:00');


$part1= $time1->diff($time2)->format('%h:%i:%s');
$part2= $time2->diff($time3)->format('%h:%i:%s');
$part3= $time3->diff($time4)->format('%h:%i:%s');

$part4 = new DateTime('00:00'); // Create a 00:00 DateTime so we can use it for calculation
$part4Clone = clone $part4;
$part4->add($time1->diff($time2)); // Add $part1 (difference between $time1 and $time2)
$part4->add($time2->diff($time3)); // Add $part2 (difference between $time2 and $time3)
$part4 = $part4->diff($part4Clone)->format('%h:%i:%s'); // Calculate difference between 00:00 and $part1+$part2 and format it accordingly

var_dump($part1,$part2,$part3,$part4);

https://3v4l.org/B8Im8

  

5.6.38-7.3.0rc4的输出

     

string(6)“ 0:59:0”

     

string(6)“ 0:30:0”

     

string(5)“ 1:0:0”

     

string(6)“ 1:29:0”

答案 1 :(得分:1)

创建一个DateTime并将其设置为例如午夜00:00:00date_diff返回一个DateInterval,您可以将其添加到Datetime。终于从午夜再次获得差异。

$part4 = (new DateTime('midnight'))
    ->add(date_diff($time2, $time1))
    ->add(date_diff($time4,$time3))
    ->diff(new DateTime('midnight'))
    ->format('%h:%i:%s');

echo $part4; // 1:59:0

Demo