Advertisement
Virajsinh

calculate the difference between two times in PHP in both HH:MM:SS format and decimal format in PhP

May 6th, 2024 (edited)
808
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.97 KB | Source Code | 0 0
  1. <?php
  2.     $start_time = "09:00 PM"; //    $start_time = "21:00:00";
  3.     $end_time = "08:12 AM";   //    $end_time = "08:12:00";
  4.  
  5.     $time_format_A = DateTime::createFromFormat("h:i A", $start_time);
  6.     $time_format_B = DateTime::createFromFormat("H:i:s", $start_time);
  7.     if($time_format_A !== false){
  8.         $start_datetime = DateTime::createFromFormat("h:i A", $start_time);
  9.         $end_datetime   = DateTime::createFromFormat("h:i A", $end_time);
  10.     }elseif($time_format_B !== false){
  11.         $start_datetime = DateTime::createFromFormat("H:i:s", $start_time);
  12.         $end_datetime   = DateTime::createFromFormat("H:i:s", $end_time);
  13.     }else{
  14.         return "";
  15.     }
  16.  
  17.     // --------------------------------------------------------------
  18.     // $start_time = "09:00 PM";
  19.     // $end_time = "08:12 AM";
  20.  
  21.     // Create DateTime objects for start and end times
  22.     // $start_datetime = DateTime::createFromFormat('h:i A', $start_time);
  23.     // $end_datetime = DateTime::createFromFormat('h:i A', $end_time);
  24.     // --------------------------------------------------------------
  25.     // $start_time = "08:54:00";
  26.     // $end_time = "12:21:00";
  27.  
  28.     // Convert times to DateTime objects
  29.     // $start_datetime = DateTime::createFromFormat('H:i:s', $start_time);
  30.     // $end_datetime = DateTime::createFromFormat('H:i:s', $end_time);
  31.     // --------------------------------------------------------------
  32.  
  33.     // If end time is before start time, it means it's on the next day
  34.     if($end_datetime < $start_datetime) {
  35.         $end_datetime->modify('+1 day'); // Add 1 day to end time
  36.     }
  37.  
  38.     // Calculate the difference as a DateInterval
  39.     $interval = $start_datetime->diff($end_datetime);
  40.  
  41.     // Format the difference as HH:MM:SS
  42.     $time_difference = $interval->format('%H:%I:%S');
  43.  
  44.     // Convert the difference to decimal hours
  45.     $total_seconds = $interval->s + $interval->i * 60 + $interval->h * 3600;
  46.     $decimal_hours = $total_seconds / 3600;
  47.  
  48.     echo "Difference (HH:MM:SS): " . $time_difference . "<br>";
  49.     echo "Difference (Decimal hours): " . number_format($decimal_hours, 2);
  50. ?>
Tags: php
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement