Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php calculate hours elapsed from PM to AM

Tags:

php

datetime

time

Time is confusing... How can one calculate the time elapsed from PM to AM in php?

For example 22:00:00 (10pm) to 02:00:00 (02am) should give 04 hours elapsed. Instead my code returns -08 hours

function hours_elapsed() 
{           
    $timestart = strtotime("22:00:00");
    $timestop = strtotime("02:00:00"); 

    $time_diff = $timestop - $timestart; //time difference

    return gmdate("h", $total_hours);
}

It's clear that the code calculates in 24 hour format so of course it returns -08 but how is it possible to get time elapsed without 24 hour constraint.. when it passes the midnight mark?

like image 868
CyberJunkie Avatar asked Dec 26 '22 23:12

CyberJunkie


1 Answers

-8 hours is 4 hours. Just add 12 if the number is negative:

$time_diff = $timestop - $timestart; //time difference

if ($time_diff < 0) {
  $time_diff += 12;
}

This won't help you, however, if your dates are more than one day apart. You need to specify the date as well (as in the day of the month) to tell PHP that those times are different.

like image 156
Blender Avatar answered Jan 11 '23 22:01

Blender