PHP – Calculating how many times ago (5 seconds, 5 hours, 5 days, 5 years …)

I took a PHP function allowing to compare two dates and tell their difference in seconds, minutes, hours, days etc like:

“5 minutes ago”,
“5 years ago”, etc

The problem is that each time an hour is missing on the departure date. Living in France, the DateTimeZone is “Europe / Paris”.

I have this function:

public function dateDiff($time1, $precision = 6) {

    $time2 = new DateTime('now', new DateTimeZone("Europe/Paris"));
    $time2 = $time2->getTimestamp();

    // If not numeric then convert texts to unix timestamps
    if (!is_int($time1))
    {
        $time1 = strtotime($time1);
    }
    if (!is_int($time2))
    {
        $time2 = strtotime($time2);
    }

    // If time1 is bigger than time2
    // Then swap time1 and time2
    if ($time1 > $time2)
    {
        $ttime = $time1;
        $time1 = $time2;
        $time2 = $ttime;
    }

    // Set up intervals and diffs arrays
    $intervals = array('year','month','day','hour','minute','second');
    $tabIntervals = [
        'year' => 'année',
        'month' => 'mois',
        'day' => 'jour',
        'hour' => 'heure',
        'minute' => 'minute',
        'second' => 'seconde'
    ];

    $diffs = array();

    // Loop thru all intervals
    foreach ($intervals as $interval)
    {
        // Create temp time from time1 and interval
        $ttime = strtotime('+1 ' . $interval, $time1);
        // Set initial values
        $add = 1;
        $looped = 0;
        // Loop until temp time is smaller than time2
        while ($time2 >= $ttime)
        {
            // Create new temp time from time1 and interval
            $add++;
            $ttime = strtotime("+" . $add . " " . $interval, $time1);
            $looped++;
        }

        $time1 = strtotime("+" . $looped . " " . $interval, $time1);
        $diffs[$interval] = $looped;
    }

    $count = 0;
    $times = array();
    // Loop thru all diffs
    foreach ($diffs as $interval => $value) {
        $intervalFR = $tabIntervals[$interval];
        // Break if we have needed precission
        if ($count >= $precision)
        {
            break;
        }

        // Add value and interval 
        // if value is bigger than 0
        if ($value > 0)
        {
            // Add s if value is not 1
            if ($value != 1)
            {
                $intervalFR .= "s";
            }
            // Add value and interval to times array

            $times[] = $value . " " . $intervalFR;
            $count++;
        }
    }

    // Return string with times
    return "Il y a " . implode(", ", $times);
}

And by example if :

$time1 = 2019-12-16 10:00 => 1576486800
$time2 = 2019-12-16 11:50 => 1576493400

With $precision = 1, I’ve :

50 minutes and not 1 hour

Can someone help me please ?

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *