Jump to content

PHP TIME (NOT TIMEDATE) difference


KillGorack

Recommended Posts

Hi,

Trying to figure out a way to get a time difference between two times assuming they are in order..

For example; in the array below the days is easy.. because the time happens later, however nights it becomes a little more confusing.

The method I'm using now is;

  • if the dates are in order just stick a reference date on there, and get a difference.
  • If they seem to be reversed, I stick a reference date on the first one and a reference date +1 days on the second and get the difference.

Can you all think of a better way?

I will use the assumption that the times will NEVER be more than 24 hrs apart..

 

Array
(
    [2] => Array
        (
            [days] => Array
                (
                    [0] => 07:00:00
                    [1] => 15:45:00
                )

            [nights] => Array
                (
                    [0] => 15:30:00
                    [1] => 02:15:00
                )

        )

 

Link to comment
Share on other sites

current code, a little better

      function sec_diff_time($s, $e){
        if(!validateDate($s, "H:i:s") or !validateDate($e, "H:i:s")){
          return false;
        }else{
          $secsday = 86400;
          if(strtotime($s) <= strtotime($e)){
            $secs = strtotime($e) - strtotime($s);
          }else{
            $secs = (strtotime($e) + $secsday) - strtotime($s);
          }
          return $secs;
        }
      }

 

Link to comment
Share on other sites

Given the parameters of your question, I can't think of any meaningful improvement.  If I was to quibble with the design of this,  your function sec_diff_time() is misleading, because you have baked in the normalization rule.  

While functionally no different from what you have, I'd try not to compute strtotime over and over simply to do your comparison, given that the result is a unix timestamp integer. 

Again, just a quibble but there is no benefit in your code to set the constant for seconds in a day to a variable prior to use, since you aren't using it in multiple places.

If it's really a constant then this is a case where a PHP define('SECONDS_PER_DAY", 86400) constant is appropriate and wouldn't be wonky in use.

 

function sec_diff_time($s, $e){
    if (!validateDate($s, "H:i:s") or !validateDate($e, "H:i:s")) {
      return false;
    } else {
      $startTS = strtotime($s);
      $endTS = strtotime($e);
      
      $endTS = $startTS > $endTS ? $endTS + 86400 : $endTS; 
      return $endTS - $startTS;
    }
}

 

Link to comment
Share on other sites

My preference is to use dateTime functions

foreach ($data as $period => $times) {
    echo "$period " . calcDiff($times[0], $times[1]) . '<br>';
    
}

function calcDiff($tstr1, $tstr2)
{
    $t1 = new DateTime($tstr1);
    $t2 = new dateTime($tstr2);
    if ($t2 < $t1) $t2->modify('+1 days');
    $diff = $t2->diff($t1);
    return  sprintf('%d:%02d:%02d', $diff->h, $diff->i, $diff->s);
}

giving

days 8:45:00
nights 10:45:00

 

Link to comment
Share on other sites

This code does the trick.  Some examples I found used the floor function which causes a problem with negative differences.  The intval() corrects that.

$secs_per_hr = 60*60;
// example 1
$dt1 = strtotime('07:00:00');
$dt2 = strtotime('15:45:00');
echo "Example 1<br>date1 is ".date('H:i:s a',$dt1). ' and date 2 is '.date('H:i:s a',$dt2).'<br>';

$diff = $dt2 - $dt1;
$hours = intval($diff / $secs_per_hr);
$minutes = $diff - ($hours * $secs_per_hr);
echo 'Ex. #1 - Elapsed time is: ' . $hours .  ' hours, ' . ( $minutes / 60 ) . ' minutes<br>';
//echo "Diff is $diff<br>";
echo "<br><br>";


// example 2
$dt1 = strtotime('15:30:00');
$dt2 = strtotime('02:15:00');
echo "Example 2<br>date1 is ".date('H:i:s a',$dt1). ' and date 2 is '.date('H:i:s a',$dt2).'<br>';

$diff = $dt2 - $dt1;
$hours = intval($diff / $secs_per_hr);
$minutes = $diff - ($hours * $secs_per_hr);
echo 'Ex. #2 - Elapsed time is: ' . $hours .  ' hours, ' . ( $minutes / 60 ) . ' minutes<br>';
//echo "Diff is $diff<br>";
echo "<br><br>";


// reverse of ex 2
$diff = $dt1 - $dt2;
$hours = intval($diff / $secs_per_hr);
$minutes = $diff - ($hours * $secs_per_hr);
echo 'Ex. #3 - Reverse of #2 is: ' . $hours .  ' hours, ' . ( $minutes / 60 ) . ' minutes<br>';
//echo "Diff is $diff<br>";
echo "<br><br>";

 

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.