skip to Main Content

I have these PHP codes where I wanted to calculate the time difference between 2 given time.

// This is 2:00 am o'clock 
$time1 = 02:00;

// This is 9 pm o'clock
$time2 = 21:00;

I want to calculated backwards time difference between 2am – 9pm, So the time difference should be 5hrs.

I tried the following but did not get the correct result:

$diff = date('H:i:s a', strtotime($time1)) - date('H:i:s a', strtotime($time2));

echo $diff;

2

Answers


  1. Online Demo: https://onecompiler.com/php/42kbtdbzt

    <?php
    // Define the time variables
    $time1 = "02:00";
    $time2 = "21:00";
    
    // Convert the time strings to DateTime objects
    $datetime1 = DateTime::createFromFormat('H:i', $time1);
    $datetime2 = DateTime::createFromFormat('H:i', $time2);
    
    // Calculate the difference between the two times
    $interval = $datetime1->diff($datetime2);
    
    // Calculate the total minutes of the time difference
    $totalMinutes = ($interval->h * 60) + $interval->i;
    
    // Calculate the total minutes in a day
    $minutesInDay = 24 * 60;
    
    // Subtract the time difference from 24 hours
    $remainingMinutes = $minutesInDay - $totalMinutes;
    
    // Convert the remaining minutes back to hours and minutes
    $remainingHours = floor($remainingMinutes / 60);
    $remainingMinutes = $remainingMinutes % 60;
    
    
    // Display the Time difference
    echo "Time difference: " . $interval->format('%H hours %I minutes') ."n";
    
    // Display the remaining time
    echo "Backwards time difference: " . $remainingHours . " hours " . $remainingMinutes . " minutesn";
    
    ?>
    
    Login or Signup to reply.
  2. <?php
    
    $time1 = "21:00"; // 9:00 PM
    $time2 = "02:00"; // 2:00 AM
    
    // Convert the time strings to DateTime objects
    $datetime1 = DateTime::createFromFormat('H:i', $time1);
    $datetime2 = DateTime::createFromFormat('H:i', $time2);
    
    // Calculate the time difference, accounting for crossing midnight
    if ($datetime1 > $datetime2) {
        // Case where time2 is on the next day
        $datetime2->modify('+1 day');
    }
    
    $interval = $datetime1->diff($datetime2);
    
    
    echo "Backward Time interval: " . $interval->format('%H hours %I minutes') . "n";
    
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search