Return time and minutes difference with PHP

3

I have this simple file:

test.php

  <?php

  $date1='2018-01-09 16:14:01';
  $date2='2018-01-09 17:30:04';

  $dateS1 = new \DateTime($date1);
  $dateS2 = new \DateTime($date2);

  $dateDiff = $dateS1->diff($dateS2);
  $result = $dateDiff->h . ' horas e ' . $dateDiff->i . ' minutos';
  echo $result;
  ?>

In theory I should return the difference in hours and minutes, however, I only get back a blank page.

Do you think it could be the PHP version on my machine? I use version 5.1.6

    
asked by anonymous 10.01.2018 / 14:17

3 answers

6

According to the PHP Documentation the version must be greater than or equal to 5.3

PHP DateTime :: diff

For your version I found a Question already that can help you.

    
10.01.2018 / 14:40
3

I've replicated your code in this website that contains the php server with 5.1.6 and it has a fatal error pois a classe nao está definida.

and as already stated in the php documentation the class datetime.diff is valid for php 5.3 or higher

    
10.01.2018 / 14:25
2

As already replied, the class DateTime is available in versions PHP 5 >= 5.2.0 e PHP 7 .

What you can do around it is:

$data1 = '2018-01-09 16:14:01';
$data2 = '2018-01-09 17:30:04';

$unix_data1 = strtotime($data1);
$unix_data2 = strtotime($data2);

$nHoras   = ($unix_data2 - $unix_data1) / 3600;
$nMinutos = (($unix_data2 - $unix_data1) % 3600) / 60;

printf('%02d:%02d', $nHoras, $nMinutos); // 01:16

Example on ideone

    
10.01.2018 / 17:42