How to return the difference in hours between two dates?

Asked

Viewed 10,851 times

4

I have two dates stored in the variables $date1 and $date2 respectively. They are in format:

YYYY/MM/DD HH:MM

I wonder how I get the difference in hours between these two dates?

  • Which bank? or want to do this in PHP?

  • 1

    Do in PHP rsrs

2 answers

10


You can use the DateTime::diff to know the interval between two dates, to know the difference in hours, you get the difference in days and multiply by 24.

$datatime1 = new DateTime('2015/04/15 00:00:00');
$datatime2 = new DateTime('2015/05/16 00:00:00');

$data1  = $datatime1->format('Y-m-d H:i:s');
$data2  = $datatime2->format('Y-m-d H:i:s');

$diff = $datatime1->diff($datatime2);
$horas = $diff->h + ($diff->days * 24);

echo "A diferença de horas entre {$data1} e {$data2} é {$horas} horas";

Exemplo

  • I have just applied your method. It works well, but it is not exact in a matter of hours. For example, there’s a 16-hour interval between dates, he’ll interpret that as 0 days, and multiplying by 24 will give 0, not 16 understand? Only in this part I’m in trouble, otherwise it works perfectly.

  • Now yes it worked perfectly. And minutes would be like this? $minutos = $diff->m + ($diff->days * 1440);

  • 1

    @Guilherme I think just multiply the hours by 60, see a example.

  • Perfect! Solved :) Thank you very much.

  • Friend are not changing the result "minutes" if modified the hour and minutes in $datatime2

1

<?php
$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");

$interval = date_diff($date1, $date2);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.