Calculate time interval in hours and minutes considering different days [duplicate]

1

At the moment I have this code that is calculating the interval between the hours. I want to increment the calculation with minutes, and I want to make some changes in the logic, for example when I put the input time as 23 hours and output time as 12 hours the other day, it returns me 11 hours, and it should return 13 .

<?php 
$hi = 23;
$hf = 12;
$total = -1;

$maior = calculaMaior($hi,$hf);
$menor = calculaMenor($hi,$hf);

for($i = $maior ; $i >= $menor ; $i--){
    $total++;
    echo"<br>$total<br>";//aqui ele irá mostrar todos os números só pra garantir
}
$aux = $maior + $total;
$total  = $aux - $total;
echo "<br>**************$total*************";

function calculaMaior($n1, $n2){
    if($n1 > $n2){
        return $n1;
    }else if($n1 < $n2){
        return $n2;
    }
}
function calculaMenor($n1, $n2){
    if($n1 > $n2){
        return $n2;
    }else if($n1 < $n2){
        return $n1;
    }
}
?>
    
asked by anonymous 28.08.2016 / 05:15

2 answers

8
For deadlines of 24 hours or more, you may want to use date:

It is necessary to specify the date in these cases, for disambiguation.

PHP already has very efficient date functions to use in mathematical calculations, avoiding the use of data classes that are complex and inefficient for punctual things.

To convert a date to timestamp (which is numeric type) we have a:

gmmktime( hora, minuto, segundo, mes, dia, ano )

Caution , as is PHP, of course the order of the parameters is meaningless. Note that the month comes before the day.

See how to use:

<?php

    $entrada = gmmktime(  23, 30, 00, 05, 25, 2010 );
    $saida   = gmmktime(  11, 15, 00, 05, 26, 2010 );

    echo ( $saida - $entrada ) / 3600;

Note that you did not even need to create a function, it's pure mathematics.

To format the output, it's very simple:

<?php

    $entrada = gmmktime(  23, 30, 00, 05, 25, 2010 );
    $saida   = gmmktime(  11, 15, 00, 05, 26, 2010 );
    $diferenca = abs( $saida - $entrada );

    printf( '%d:%d', $diferenca/3600, $diferenca/60%60 );

See working at PHP Sandbox .

28.08.2016 / 14:00
0

Time calculation depends on the date.

The routine you created does not consider the date, so it returns the literal value of 11.

Here's a simulation of what you're doing, however using the DateTime class, native to PHP:

// Create two new DateTime-objects...
$date1 = new DateTime('2016-08-28T23:00:00'); // pode definir sem a letra T, assim "2016-08-28 23:00:00". O importante é que tenha o formato ISO 8601
$date2 = new DateTime('2016-08-28T12:00:00');


// The diff-methods returns a new DateInterval-object...
$diff = $date2->diff($date1);

// Call the format method on the DateInterval-object
echo $diff->format('%a Day and %h hours');

As I understood the question, the 12:00 am would be the next day, so it's a date the next day:

// Create two new DateTime-objects...
$date1 = new DateTime('2016-08-28T23:00:00');
$date2 = new DateTime('2016-08-29T12:00:00');


// The diff-methods returns a new DateInterval-object...
$diff = $date2->diff($date1);

// Call the format method on the DateInterval-object
echo $diff->format('%a Day and %h hours');

The above format are didactic examples. For something more objective, try this:

$date1 = new DateTime('2016-08-28T23:00:00');
$date2 = new DateTime('2016-08-29T12:00:00');

$diff = $date2->diff($date1);

$hours = $diff->h;
$hours = $hours + ($diff->days*24);

echo $hours;

For more details:

Alternatively, you can achieve the same result using functions like strtotime (), gmmktime (), and more, but it does not make any difference in performance. Both run in the same amount of time. One small difference is that the final memory consumption has a difference of 1.3kb with DateTime, however, at peak memory usage the difference is 400 bytes longer for the DateTime library.
Note that this time may vary according to the environment and was done without any optimization. Using an opcache would make the difference null, for example.

The difference in this cost would be relevant if it ran in a massive process of long duration and without any optimization running everything with reductions like crazy.

Finally, everything comes at a cost. You can choose to mount all this by adding a puzzle of old functions with parameters "without a friendly and logical pattern" and complaining that PHP is bad (something like mimizento), or using a library that was created to correct this mess and bring more functionalities.

Particularly, until a while ago I preferred to avoid libraries like DateTime, but I decided to give the arm twist and use those features. They facilitate a lot in the development and maintenance, as well as in the flexibility of the system.

    
28.08.2016 / 13:43