someguyincali Posted September 11, 2016 Share Posted September 11, 2016 I have this code that I'm trying to modify. When I enter a start time for 21:00 and an end time for 07:00 The existing code returns a negative number. I would like the function to assume that midnight passes if the original code returns a negative number and calculate duration. I need it to return the duration in the same format. Thank in advance for any help. protected function getDuration($fromTime, $toTime) { list($startHour, $startMin) = explode(':', $fromTime); list($endHour, $endMin) = explode(':', $toTime); $durationMinutes = (intVal($endHour) - intVal($startHour)) * 60 + (intVal($endMin) - intVal($startMin)); $hours = $durationMinutes / 60; return number_format($hours, 2); } Quote Link to comment https://forums.phpfreaks.com/topic/302139-need-to-have-code-give-duration-of-time-over-2-days/ Share on other sites More sharing options...
Jacques1 Posted September 11, 2016 Share Posted September 11, 2016 How are you going to deal with daylight saying time? The duration between 21:00 and 07:00 is not always 10 hours. It can also be 9 or 11 hours depending on the time zone and date. So if you're dealing with concrete dates, it would make a lot more sense to pass actual timestamps to the function. The user may still just enter “21:00” and “07:00”, but your application would transform that into proper absolute timestamps. 1 Quote Link to comment https://forums.phpfreaks.com/topic/302139-need-to-have-code-give-duration-of-time-over-2-days/#findComment-1537328 Share on other sites More sharing options...
Strider64 Posted September 12, 2016 Share Posted September 12, 2016 If you want to figure out duration of time you need actually timestamps like already stated or the Date and Time. Look into the DateTime class at php.net for it has a lot of built in functions that can be used, so you don't have to reinvent the wheel. Here's an example -> <?php date_default_timezone_set("America/Detroit"); $start = '2016-09-11 12:45:00'; $end = '2016-09-13 12:59:52'; $date1 = new \DateTime($start); echo $date1->format("F d, Y"); $date2 = new \DateTime($end); $diff = $date1->diff($date2); echo "<pre>" . print_r($diff, 1) . "</pre>"; Quote Link to comment https://forums.phpfreaks.com/topic/302139-need-to-have-code-give-duration-of-time-over-2-days/#findComment-1537454 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.