Nghia Phan
Nghia Phan

Reputation: 191

Sum two different DateTime in PHP

My code:

$one = new DateTime("2018-03-15 11:53:13");
$two = new DateTime("2018-03-15 13:53:00");
$diff = $one->diff($two);
$three = new DateTime("2018-03-15 11:52:55");
$four = new DateTime("2018-03-16 11:52:57");
$difftwo = $three->diff($four);
$day = $diff->format('%H:%I:%S');
$day2 = $difftwo->format('%H:%I:%S');

$secs = strtotime($day2)-strtotime("00:00:00");
$result = date("H:i:s",strtotime($day) + $secs);

echo $result;


- $day = 01:59:47
- $day2 = 00:00:02 and 1 day
Result : 01:59:49 But I want to show : 1 01:59:49 (1 is a day result of $day2)

Can someone help me find the solution?

Upvotes: 0

Views: 187

Answers (1)

Syscall
Syscall

Reputation: 19764

You could create 2 new same date. In one of them, add your 2 intervals.

Then you could use the DateInterval object to get your value:

$one = new DateTime('2018-03-15 11:53:13');
$two = new DateTime('2018-03-15 13:53:00');
$diff = $one->diff($two);

$three = new DateTime('2018-03-15 11:52:55');
$four = new DateTime('2018-03-16 11:52:57');
$difftwo = $three->diff($four);

$d1 = new DateTime(); // Now
$d2 = new DateTime(); // Now
$d1->add($diff); // Add 1st interval
$d1->add($difftwo); // Add 2nd interval

// diff between d2 and d1 gives total interval
echo $d2->diff($d1)->format('%d %H:%I:%S') ; 

Outputs :

1 01:59:49

Upvotes: 1

Related Questions