Skip to content
Advertisement

PHP negative time calculation

If I add 1 hour and 35 minutes in PHP and subtract 4 hours, I get a remaining time of -3 hours and 30 minutes.

But correct would be -2 hours and 30 minutes. Where’s the mistake?

    $minutes = null;
    while ($z = $stmt->fetch()) {
        $minutes += $z['minutes'];
    }

   
    if ($stmt = $pdo->prepare($sql)) {
        $stmt->execute(array(
            ':user' => $user
        ));
        $negativeTime = null;
        while ($z = $stmt->fetch()) {
            $negativeTime += $z['minutes'];
        }
    }
    $minutes = $minutes - $negativeTime;

    echo (floor($minutes / 60)) . " hours and " . ($minutes - floor($minutes / 60) * 60) . " minutes";

Advertisement

Answer

$minutes - floor($minutes/60) is positive. So what you’re getting is -3 hours plus 30 minutes, which is -2:30.

You need to treat positive and negative values of $minutes differently, so that both the hours and minutes are the distance from zero. Use the abs() function to convert the time to positive, perform the calculation, then show the hours as negative if the original value of $minutes was negative.

$sign = $minutes < 0 ? '-' : '';
$minutes = abs($minutes);
$hours = floor($minutes / 60);
$minutes = $minutes % 60;

echo "$sign$hours hours and $minutes minutes";

DEMO

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement