Calculate difference of php hours

4

I have a web application where users can insert the extra hours they have done. One problem I have is that I made a function in which I calculated the difference in hours. In the application, if a user has worked less or 4 hours, those hours are paid, instead if he has worked more than 4 hours, the user has the possibility to choose if he wants to be paid or turn them into a vacation day. The problem of the function is for example:

If user1 worked on Saturday from 8:00 to 12:10, the function should let me choose but it does not leave me because although I put it until 12:59 it counts it 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');
    
asked by Xerox 06.08.2018 в 15:06
source

1 answer

2

I mention 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 you place it for the case of hours going on   hrs: minutes: seconds in quotes

Otherwise, your code is fine

Now if I put the start and end values as constants, the use of the keys that you put would be over, here I leave 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

link

    
answered by 06.08.2018 / 15:18
source