-1

Possible Duplicate:
How to calculate the difference between two dates using PHP?

I have a PHP array that holds film release dates in the form of "2012-04-04" as an example. How would i go about finding the difference of 2 dates.

For example -

2012-04-04

2012-03-31

Expected response - 5 days difference

Community
  • 1
  • 1
user1064660
  • 97
  • 1
  • 9
  • 1
    PHP >= v5.3 you can use [`date_diff`](http://php.net/manual/en/function.date-diff.php) (a.k.a. [`DateTime::diff()`](http://www.php.net/manual/en/datetime.diff.php)) – Brad Christie Mar 28 '12 at 20:39

4 Answers4

1
$d1 = new DateTime('2012-04-04');
$d2 = new DateTime('2012-03-31');

$interval = $d1->diff($d2);

echo $interval->format('%R%a days');
keithhatfield
  • 3,273
  • 1
  • 17
  • 24
  • Ive put the dates into an array, how would I find the difference between array items instead of variables? Thanks for your help – user1064660 Mar 29 '12 at 01:30
0

I wrote this function a while back to calculate the difference between dates. It will return an array of all date measurements that make up the difference.

function date_difference($date1, $date2) {
    $seconds_count = array(
        'year' => (365 * 24 * 60 * 60),
        'month' => (30 * 24 * 60 * 60),
        'day' => (24 * 60 * 60),
        'hour' => (60 * 60),
        'minute' => 60
    );

    $diff = abs($date1 - $date2);

    $years = floor($diff / $seconds_count['year']);
    $diff -=  ($years * $seconds_count['year']);

    $months = floor($diff / $seconds_count['month']);
    $diff -= ($months * $seconds_count['month']);

    $days = floor($diff / $seconds_count['day']);
    $diff -= ($days * $seconds_count['day']);

    $hours = floor($diff / $seconds_count['hour']);
    $diff -= ($hours * $seconds_count['hour']);

    $minutes = floor($diff / $seconds_count['minute']);
    $diff -= ($minutes * $seconds_count['minute']);

    $seconds = $diff;

    return array('seconds' => $seconds, 'minutes' => $minutes, 'hours' => $hours, 'days' => $days, 'months' => $months, 'years' => $years);
}
Kory Sharp
  • 490
  • 3
  • 11
0

Convert each date with strtotime(), which gives you a unix timestamp (in seconds). The subtract and see how many seconds are between the two dates. 60 * 60 * 24 is a day's worth of seconds, divide and round and you have an approximate number of days.

Surreal Dreams
  • 26,055
  • 3
  • 46
  • 61
  • I'd say this is poor advice, using the Unix timestamp has some severe limitations. Now that php has a DateTime object I strongly advise to use it rather than your suggestion. – Bazzz Mar 28 '12 at 20:52
0

What you will have to do is turn both dates into UTC format (timestamp). You can than minus them from eachother giving you the difference in seconds.

From there simply convert to days.

Difference = difference / (60 * 60 * 24).

msponagle
  • 330
  • 1
  • 11