Home » Php » datetime – How do I find the hour difference between two dates in PHP?

datetime – How do I find the hour difference between two dates in PHP?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have two dates, formated like “Y-m-d H:i:s”. I need to compare these two dates and figure out the hour difference.

How to&Answers:

You can convert them to timestamps and go from there:

$hourdiff = round((strtotime($time1) - strtotime($time2))/3600, 1);

Dividing by 3600 because there are 3600 seconds in one hour and using round() to avoid having a lot of decimal places.

Answer:

You can use DateTime class also –

$d1= new DateTime("06-08-2015 01:33:26pm"); 
$d2= new DateTime("06-07-2015 10:33:26am");
$interval= $d1->diff($d2);
echo ($interval->days * 24) + $interval->h;

Answer:

$seconds = strtotime($date2) - strtotime($date1);
$hours = $seconds / 60 / 60;

Answer:

As an addition to accepted answer I would like to remind that \DateTime::diff is available!

$f = 'Y-m-d H:i:s';
$d1 = \DateTime::createFromFormat($date1, $f);
$d2 = \DateTime::createFromFormat($date2, $f);

/**
 * @var \DateInterval $diff
 */
$diff = $d2->diff($d1);
$hours = $diff->h + ($diff->days * 24); // + ($diff->m > 30 ? 1 : 0) to be more precise

\DateInterval documentation.

Answer:

$date1 = date_create('2016-12-12 09:00:00');

$date2 = date_create('2016-12-12 11:00:00');

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

$hour = $diff->h;

Answer:

You can use strtotime() to parse your strings and do the difference between the two of them.


Resources :

Answer:

The problem is that using these values the result is 167 and it should be 168:

$date1 = "2014-03-07 05:49:23";
$date2 = "2014-03-14 05:49:23";
$seconds = strtotime($date2) - strtotime($date1);
$hours = $seconds / 60 /  60;

Answer:

This is because of day time saving.
Daylight Saving Time (United States) 2014 began at 2:00 AM on
Sunday, March 9.

You lose one hour during the period from $date1 = “2014-03-07 05:49:23” to
$date2 = “2014-03-14 05:49:23”;

Answer:

You can try this:

$dayinpass = "2016-09-23 20:09:12";
$today = time();
$dayinpass= strtotime($dayinpass);
echo round(abs($today-$dayinpass)/60/60);