#49: Finding the Difference Between Two Dates

If you find yourself in a situation where you need to know how much time has elapsed between a pair of dates, here's what you're looking for.

<?php

function calculate_time_difference($timestamp1, $timestamp2, $time_unit) {
    // Determines difference between two timestamps

    $timestamp1 = intval($timestamp1);
    $timestamp2 = intval($timestamp2);
    if ($timestamp1 && $timestamp2) {
        $time_lapse = $timestamp2 - $timestamp1;

        $seconds_in_unit = array(

          'second'   => 1,
          'minute'   => 60,
          'hour'     => 3600,
          'day'      => 86400,
          'week'     => 604800,
        );
   
        if ($seconds_in_unit[$time_unit]) {
            return floor($time_lapse/$seconds_in_unit[$time_unit]);
        }
    }
    return false;
}
?>

The calculate_time_difference() function takes three arguments: the ...

Get Wicked Cool PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.