Question:
I have a web application where users can insert the overtime they have done. One problem I have is that I made a function that calculates the difference in hours. In the application, if a user has worked less than or 4 hours, those hours are paid, whereas if they have worked more than 4 hours, the user has the possibility to choose if they want to be paid or convert it into a vacation day. The function problem is for example:
If user1 worked on Saturday from 8:00 a.m. to 12:10 p.m., the function should allow me to choose but it does not allow me because even if I put until 12:59 it counts as 4 hours instead of 4:59 hours.
Here my function:
$datetime1 = new DateTime({FECHA_INICIO});
$datetime2 = new DateTime({FECHA_FIN});
$interval = $datetime1->diff($datetime2);
return $interval->format('%H:%I:%S');
Answer:
I tell you the following, you should have your code as follows
<?php
$apertura = new DateTime('08:00:00');
$cierre = new DateTime('12:59:00');
$tiempo = $apertura->diff($cierre);
echo $tiempo->format('%H horas %i minutos');
//retornará 4:59
Look at the format that places it for the case of hours, it goes in hrs: minutes: seconds between quotes
Otherwise your code is fine.
Now if I placed the start and end values as constants, the use of the keys that you put would be superfluous, here is an example
<?php
DEFINE('HORA_INICIO', '08:00:00');
DEFINE('HORA_FIN', '12:59:00');
$apertura = new DateTime(HORA_INICIO);
$cierre = new DateTime(HORA_FIN);
$tiempo = $apertura->diff($cierre);
echo $tiempo->format('%H:%I');
Reference source
http://php.net/manual/en/datetime.diff.php