Jump to content

Need to Have Code give duration of time over 2 days


someguyincali

Recommended Posts

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);
    }
Link to comment
Share on other sites

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.

  • Like 1
Link to comment
Share on other sites

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>";

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.