1

I have 2 Datetime Objects and I used diff to get an interval. I then want to add this interval to another date to get a date in the future. Here is my code:

 $start = new DateTime($start_date);
 $stop = new DateTime($end_date);
 $interval = $start->diff($stop);
 $now = new DateTime($update_date);
 $now->add($interval);
 return $now->format('Y-m-d H:i:s');

To verify the numbers were adding up, I did this:

 echo "interval = " . $interval->format("%d days, %h hours and %i minutes");
 echo "<br/> date  = ". $update_date;
 echo "<br/> result  = ". $now->format('Y-m-d H:i:s');

and I got this:

 interval = 0 days, 0 hours and 13 minutes
 date = 2016-01-14 21:03:41
 result = 2016-01-14 20:50:22

So if Im adding 13 minutes to my date, why is the result 13 minutes less?

Severian
  • 427
  • 3
  • 18

2 Answers2

0

The following code is working for me:

$start_date = '2016-01-14 12:12:00';
$end_date = '2016-01-14 12:25:00';
$update_time = '2016-01-14 16:00:00';

$start = new DateTime($start_date);
$end = new DateTime($end_date);
$interval = $start->diff($end);
$now = new DateTime($update_time);
$now->add($interval);
echo $now->format('Y-m-d H:i:s'); //2016-01-14 16:13:00

A working example you can find here: https://3v4l.org/P3rKU

Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87
  • Nice bit of Yoda-speak at the end, you wrote. ;) – Jonathan M Jan 14 '16 at 21:40
  • You are correct sebastianbrosch, the start and end dates were out of order, the interval was in fact negative, even though it seems there is no indication from the interval. thank you, i do – Severian Jan 14 '16 at 22:28
0
$start = new DateTime('2016-01-14 21:03:41');
$end = new DateTime('2016-01-14 21:30:05');
$interval = date_diff($start,$end);
echo $interval->format("%d days, %h hours and %i minutes")."<br/>";   
$now = new DateTime('2016-01-14 21:30:05'); 
$now->add($interval);
echo "Total  : ", $now->format('Y-m-d H:i:s');

Try this.

williams
  • 31
  • 1
  • 5