ruzD ruzD - 29 days ago 8
PHP Question

PHP - Operations with date/time

I'm trying with to date/time php functions. I would like to do the basic arithmetic operations(addition, subtraction...). I have read that there are various function to do it.

I'm beginning with DateTime and date_diff.

<?php

$time1 = new DateTime ('08:10:20');

$time2 = new DateTime ('10:02:30');

$result = date_diff($time1, $time2)->format('H:i:s');

echo $result;

?>


After run it, it show:

enter image description here

Please Could you help me?

Answer

Best way will be object oriented:

$time1 = DateTime::createFromFormat('H:i:s', '08:10:20');
$time2 = DateTime::createFromFormat('H:i:s', '10:02:30');

$interval = $time1->diff($time2);
echo $interval->format('%H:%i:%s'); // print 01:52:10

I highly discourage using procedural process :

date_diff($time1, $time2);

Use object oriented as much as possible:

$interval = $time1->diff($time2);

I hope it helps

Comments