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?
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?
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";
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);
@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 php
You are not signed in. Login or sign up in order to post.
Which bank? or want to do this in PHP?
– stderr
Do in PHP rsrs
– GGirotto