-2

I want to return the difference between two datetime objects.

I tried this but is not working. Whats wrong?

<?php //php 7.0.8

    $a='2018-12-05 09:00:00';
    $b='2018-12-05 15:00:00';

    $time1 = new DateTime($a);
    $time2 = new DateTime($b);

    $interval = $time1->diff($time2);
    echo $interval->format('H:i');
?>
Constantin Groß
  • 10,719
  • 4
  • 24
  • 50
Fabio Araujo
  • 309
  • 1
  • 4
  • 13

1 Answers1

2

Each format character must be prefixed by a percent sign (%).

echo $interval->format('%H:%i');
joshas
  • 1,464
  • 1
  • 24
  • 41
  • it show odd stuff like 20:2 and 1:0 . how can I do it like 20:20 or 01:00? – Fabio Araujo Dec 22 '18 at 23:10
  • @FabioAraujo take a look at PHP documentation, there are alternative formatting options, including leading zeros: http://php.net/manual/en/dateinterval.format.php – joshas Dec 22 '18 at 23:12
  • @FabioAraujo you just need `I` instead of `i`. – Nick Dec 22 '18 at 23:20
  • %H just allow to show time between 0 and 23, there is any hour representation to show any hours you want 0 to infinit?? This is an app to log worked time and I need it to show in hours. – Fabio Araujo Dec 25 '18 at 19:39
  • @FabioAraujo There are plenty answers on StackOverflow on how to find time difference in hours, e.g. https://stackoverflow.com/a/29664921/586678 – joshas Dec 26 '18 at 19:45