Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $start_time = "09:00 PM"; // $start_time = "21:00:00";
- $end_time = "08:12 AM"; // $end_time = "08:12:00";
- $time_format_A = DateTime::createFromFormat("h:i A", $start_time);
- $time_format_B = DateTime::createFromFormat("H:i:s", $start_time);
- if($time_format_A !== false){
- $start_datetime = DateTime::createFromFormat("h:i A", $start_time);
- $end_datetime = DateTime::createFromFormat("h:i A", $end_time);
- }elseif($time_format_B !== false){
- $start_datetime = DateTime::createFromFormat("H:i:s", $start_time);
- $end_datetime = DateTime::createFromFormat("H:i:s", $end_time);
- }else{
- return "";
- }
- // --------------------------------------------------------------
- // $start_time = "09:00 PM";
- // $end_time = "08:12 AM";
- // Create DateTime objects for start and end times
- // $start_datetime = DateTime::createFromFormat('h:i A', $start_time);
- // $end_datetime = DateTime::createFromFormat('h:i A', $end_time);
- // --------------------------------------------------------------
- // $start_time = "08:54:00";
- // $end_time = "12:21:00";
- // Convert times to DateTime objects
- // $start_datetime = DateTime::createFromFormat('H:i:s', $start_time);
- // $end_datetime = DateTime::createFromFormat('H:i:s', $end_time);
- // --------------------------------------------------------------
- // If end time is before start time, it means it's on the next day
- if($end_datetime < $start_datetime) {
- $end_datetime->modify('+1 day'); // Add 1 day to end time
- }
- // Calculate the difference as a DateInterval
- $interval = $start_datetime->diff($end_datetime);
- // Format the difference as HH:MM:SS
- $time_difference = $interval->format('%H:%I:%S');
- // Convert the difference to decimal hours
- $total_seconds = $interval->s + $interval->i * 60 + $interval->h * 3600;
- $decimal_hours = $total_seconds / 3600;
- echo "Difference (HH:MM:SS): " . $time_difference . "<br>";
- echo "Difference (Decimal hours): " . number_format($decimal_hours, 2);
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement