Error when setting time difference with Datetime after 00:00

1

I have a problem finding the time between two times with datetime when the exit time is between midnight and one in the morning.

For example, if the first time is 14:00, and the second is 23:00, it returns certain:

  

9 hours

But if the second time is 00:00, it returns:

  

14 hours

When should I return 10 hours.

If I put the second time at 01:00, it still returns wrong:

  

13 hours

But if I put 2:00, then it already returns right again:

  

12 hours

HTML:

 <label for="Cseg5">Entrada:</label>
 <input type="time" id="Cseg5" name="Tsegsss">
 <label for="Cseg6">Saída:</label>
 <input type="time" id="Cseg6" name="Tsegssss"> 

PHP:

$val1 = $_POST ["hora1"];
$val2 = $_POST ["hora2"];

$datetime1 = new DateTime($val1);
$datetime2 = new DateTime($val2);

$intervalo = $datetime1->diff($datetime2);

To transform the property into a variable:

$horario1 = $intervalo->h;

This is followed by var_dump of $ val1, $ val2, $ schedule1, and $ interval, with fields filled in at 2:00 p.m. and 12:00 p.m.

  

string (5) "14:00"

     

string (5) "00:00"

     

int (14)

     

object (DateInterval) # 30 (15) {["y"] = > int (0) ["m"] = > int (0) ["d"] = >   int (0)    ["h"] = > int (14) ["i"] = > int (0) ["s"] = > int (0) ["weekday"] = > int (0) ["weekday_behavior"] = > int (0) ["first_last_day_of"] = > int (0)   ["invert"] = > int (1) ["days"] = > int (0) ["special_type"] = > int (0)   ["special_amount"] = > int (0) ["have_weekday_relative"] = > int (0)   ["have_special_relative"] = > int (0)}

From what I understand it is subtracting backwards when it is past midnight (until 1 o'clock). I've already tried to invert the variables ...

 $intervalo = $datetime2->diff($datetime1);

But it did not work. Any idea?

    
asked by anonymous 18.04.2015 / 04:45

1 answer

1

Problem

To calculate the expected time interval, it is necessary to inform the date and time so the datetime object knows if it is the same day or different days.

In your example, if you run a print_r in $datetime1 and $datetime2 , only the time will print something like:

$ datetime1:

DateTime Object
(
    [date] => 2015-04-18 14:00:00
    [timezone_type] => 3
    [timezone] => America/New_York
)

$ datetime2

DateTime Object
(
    [date] => 2015-04-18 00:00:00
    [timezone_type] => 3
    [timezone] => America/New_York
)

Solution

When calculating difference of dates / hours returns negative invert of object DateInterval returns 1, in this case just add a day in $datetime2 and calculate the difference again.

function calcularIntervaloHoras($horaInicio, $horaFim){
    $intervalo = $horaInicio->diff($horaFim);

    if($intervalo->invert == 1){
       $horaFim->add(new DateInterval('P1D'));
       $intervalo = $horaInicio->diff($horaFim);   
    }

    return $intervalo;

}

phpfiddle - example

    
18.04.2015 / 06:30