简体   繁体   中英

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

I have two dates, formated like "Ymd H:i:s". I need to compare these two dates and figure out the hour difference.

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.

You can use DateTime class also -

$d1= new DateTime("06-08-2015 01:33:26pm"); // first date
$d2= new DateTime("06-07-2015 10:33:26am"); // second date
$interval= $d1->diff($d2); // get difference between two dates
echo ($interval->days * 24) + $interval->h; // convert days to hours and add hours from difference
$seconds = strtotime($date2) - strtotime($date1);
$hours = $seconds / 60 / 60;

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.

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;
$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;

You can try this :

    $time1 = new DateTime('06:56:58');
    $time2 = new DateTime('15:35:00');
    $time_diff = $time1->diff($time2);
    echo $time_diff->h.' hours';
    echo $time_diff->i.' minutes';
    echo $time_diff->s.' seconds';

Output:

8 hours 38 minutes 2 seconds

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


Resources :

You can try this:

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

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM