Search code examples
phpdatetimeepoch

Get Difference Between Two Times (Unix Epoch)


You know when it's late in the night and your brain is fried? I'm having one of those nights right now, and my function so far is not working as it should, so please take a look at it: (I should note that I'm using the PHP 5.2.9, and the function / method DateTime:Diff() is not available until PHP 5.3.0.

<?php
    function time_diff($ts1, $ts2) {
        # Find The Bigger Number
        if ($ts1 == $ts2) {
            return '0 Seconds';
        } else if ($ts1 > $ts2) {
            $large = $ts1;
            $small = $ts2;
        } else {
            $small = $ts1;
            $large = $ts2;
        }
        # Get the Diffrence
        $diff = $large - $small;
        # Setup The Scope of Time
        $s = 1;         $ss = 0;
        $m = $s * 60;   $ms = 0;
        $h = $m * 60;   $hs = 0;
        $d = $h * 24;   $ds = 0;
        $n = $d * 31;   $ns = 0;
        $y = $n * 365;  $ys = 0;
        # Find the Scope
        while (($diff - $y) > 0) { $ys++; $diff -= $y; }
        while (($diff - $n) > 0) { $ms++; $diff -= $n; }
        while (($diff - $d) > 0) { $ds++; $diff -= $d; }
        while (($diff - $h) > 0) { $hs++; $diff -= $h; }
        while (($diff - $m) > 0) { $ms++; $diff -= $m; }
        while (($diff - $s) > 0) { $ss++; $diff -= $s; }
        # Print the Results
        return "$ys Years, $ns Months, $ds Days, $hs Hours, $ms Minutes & $ss Seconds.";
    }
    // Test the Function:
    ediff(strtotime('December 16, 1988'), time());
    # Output Should be:
    # 20 Years, 11 Months, 8 Days, X Hours, Y Minutes & Z Seconds.
?>

Solution

  • How about this:

    function time_diff($t1, $t2)
    {
       $totalSeconds = abs($t1-$t2);
       $date = getdate($totalSeconds); 
       $firstYear = getdate(0);
       $years = $date['year']-$firstYear['year'];
       $months = $date['mon'];
       $days = $date['mday'];
       $hours = $date['hour'];
       $minutes = $date['minutes'];
       $seconds = $date['seconds'];
    
       return "$years Years, $months Months, $days Days, $hours Hours, $minutes Minutes & $seconds Seconds.";
    }
    

    This uses the difference of the given times as a date. Then you can let the "getdate" do all the work for you. The only challenge is the number years - which is simply the getdate year (of the difference) minus the Unix epoch year (1970).

    If you don't like using an actual month, you could also divide the "year" day by the number of days in 12 equal months

    $months = $date['yday'] / (365/12);
    

    Similarly days could be figured out the remaining days with modulus

    $days = $date['yday'] % (365/12);