PHP: add differences from two DateTime objects to another date using DateTime :: modify

How to add the difference between two DateTime objects to another DateTime object? I tried code like the one below, but that didn't work.

$first_time=new DateTime('01/01/2000 00:00:00'); $second_time=new DateTime('01/01/2000 00:00:50'); $diff=$first_time->diff($second_time); $time=new DateTime('01/01/2012 12:00:00'); $time->modify('+'.$diff->format('%s').' seconds'); echo $time; //Should echo: "01/01/2012 12:00:50" 

Can someone help me?

+4
source share
1 answer

format() does not calculate the absolute number of seconds of an Interval, it just gives you the values ​​of internal attributes. Since you want to add, why not just use add() ? diff() returns a DateInterval object, and this is what add() needs.

 $first_time=new DateTime('01/01/2000 00:00:00'); $second_time=new DateTime('01/01/2000 00:00:50'); $diff=$first_time->diff($second_time); $time=new DateTime('01/01/2012 12:00:00'); $time->add($diff); echo $time; 
+3
source

Source: https://habr.com/ru/post/1399640/


All Articles