1

Possible Duplicate:
Calculate number of hours between 2 dates in PHP

How can I get the number of hours of difference between two dates in PHP? I need to get an integer since I want to know if is bigger or smaller than a particular value.

Community
  • 1
  • 1
Hommer Smith
  • 26,772
  • 56
  • 167
  • 296

3 Answers3

4

Try:

 $date1 = "2012-11-05 12:35:00";
 $date2 = "2012-11-07 14:35:00"; 
 $diff = strtotime($date2) - strtotime($date1);
 $diff_in_hrs = $diff/3600;
 print_r($diff_in_hrs);

Manual

Demo

Teena Thomas
  • 5,139
  • 1
  • 13
  • 17
2

If you have an up-to-date PHP

$dateOne = new DateTime('2012-01-20 00:00:00');
$dateTwo = new DateTime('2012-01-21 02:00:00');

// Procedurally $interval = date_diff($dateOne, $dateTwo);

// Alternatively OOP style if supported
$interval = $dateOne->diff($dateTwo);

See: http://www.php.net/manual/en/class.dateinterval.php

Martin Lyne
  • 3,157
  • 2
  • 22
  • 28
  • 1
    You'll get `undefined function date_diff` or `unknown method diff` if it's not up to date. Or just check `php -v` / `phpinfo()` – Martin Lyne Nov 13 '12 at 18:23
  • you will recieve a Fatal error if you do not set the default timezone (`date_default_timezone_set()`) – Samuel Cook Nov 13 '12 at 18:25
  • You set that in your php.ini `date.timezone = 'Europe/London';` or using `date_default_timezone_set()` function http://php.net/manual/en/function.date-default-timezone-set.php – Martin Lyne Nov 13 '12 at 18:28
1
<?php
$time1 = time();
$time2 = mktime(0,0,0,11,13,2012); // earlier today
echo ($time1 - $time2) / 3600; // 3600 seconds in hour
?>
Samuel Cook
  • 16,620
  • 7
  • 50
  • 62