How to subtract between 2 hours in PHP

2

I'm using Codeigniter and I want to subtract it in the view.

<?php
    $cadena = strtotime($seguimiento->horaInicio);
    $cadena = date("H:i", $cadena);
    echo $cadena;

    $cadena2 = strtotime($seguimiento->horaTermino);
    $cadena2 = date("H:i", $cadena2);
    echo $cadena2;

    $res = abs($cadena - $cadena2);
    echo $res;
?>

In case the hour is 11:30 16:15 the result should be 4,85 but instead it shows me 5 . I hope you have explained me well.

   var HDesde = $(this).data("inicio");
       var HHasta = $(this).data("fin");


       // var dia = $(this).data("dia");
       // if (i=0) { fecha = dia; }

       hora1 = (HDesde).split(":");
       hora2 = (HHasta).split(":");
       HoraDesde=(hora1[0]);
       MinutoDesde=(hora1[1]);
       HoraHasta=(hora2[0]);
       MinutoHasta=(hora2[1]);
       TotDesde=parseInt((HoraDesde*60)) + parseInt(MinutoDesde);
       TotHasta=parseInt(HoraHasta*60) + parseInt(MinutoHasta);
       RestaHoras=(TotHasta - TotDesde);
       TotHorasTrab=(RestaHoras / 60).toFixed(2);

       $(this).html(TotHorasTrab);
    
asked by MoteCL 04.07.2018 в 15:11
source

3 answers

4

You could use the diff php.

feature
  

Returns the difference between two DateTimeInterface objects.

$horaInicio = new DateTime($cadena);
$horaTermino = new DateTime($cadena2);

$interval = $horaInicio->diff($horaTermino);
echo $interval->format('%H horas %i minutos %s seconds');

The variable $interval comes to the type DateInterval ; if you want to operate with that variable, for example to add it to another date you can use the function add :

$nuevaFecha = new DateTime('2018-07-04 00:00:00');
$nuevaFecha->add($interval);
echo $nuevaFecha->format('Y-m-d H:i:s');
    
answered by 04.07.2018 / 15:29
source
0

The point is that you need two valid DateTime objects to use diff . From there you can obtain an object DateInterval with diff . Then you can take advantage of the properties of that object to make the calculations you need.

For example:

$fechaUno=new DateTime('11:30');
$fechaDos=new DateTime('16:15');

$dateInterval = $fechaUno->diff($fechaDos);
echo $dateInterval->format('Total: %H horas %i minutos %s segundos').PHP_EOL;

You have the exit:

Total: 04 horas 45 minutos 0 segundos

If you check inside your object $dateInterval you will see what it contains:

We do var_dump($dateInterval); and we will have:

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

Suppose you now want to calculate how many minutes you have. You apply appropriate calculations to the properties d, h, i of the object (days, hours, minutes):

$totalMinutos=($dateInterval->d * 24 * 60) + ($dateInterval->h * 60) + $dateInterval->i;
echo "Total minutos: $totalMinutos";

You will have at the exit:

Total minutos: 285

Another way

Another thing you could do would be to obtain the timestamp of the two objects, subtract their value and make operations with it.

Let's see:

$totalSegundos = abs($fechaUno->getTimestamp() - $fechaDos->getTimestamp());
$totalMinutos=$totalSegundos/60;

echo "Total segundos: $totalSegundos";
echo PHP_EOL;

echo "Total minutos: $totalMinutos";
echo PHP_EOL;

echo "Representación Horas,Minutos: ".gmdate("H:i", $totalSegundos);

The output in this case would be:

Total segundos: 17100
Total minutos: 285
Representación Horas,Minutos: 04:45

Cumulative calculation using a loop

Let's assume that your object is similar to this one.

You can create a function that calculates the total of seconds, you accumulate in the variable and at the end you use that total to represent the data as you need it:

/*Simulacro de tu objeto*/
$seguimiento=(object)array(
                            (object)array("horaInicio"=>"11:30", "horaTermino"=>"16:15"),
                            (object)array("horaInicio"=>"10:00", "horaTermino"=>"11:00")
                           );
/*Variable acumulativa*/
$totalSegundos=0;
foreach($seguimiento as $item){
    /*Se incrementa cada vez con lo que arroje la función calculateTime*/
    $totalSegundos+=calculateTime($item->horaInicio,$item->horaTermino);
}

/*Prueba de datos resultantes*/
echo "Total segundos: $totalSegundos";
echo PHP_EOL;

$totalMinutos=$totalSegundos/60;

echo "Total minutos: $totalMinutos";
echo PHP_EOL;

echo "Representación Horas,Minutos: ".gmdate("H:i", $totalSegundos);

/*Función que es llamada cada vez desde el bucle*/
function calculateTime($horaUno, $horaDos){
    $fechaUno=new DateTime($horaUno);
    $fechaDos=new DateTime($horaDos);
    $diff = abs($fechaUno->getTimestamp() - $fechaDos->getTimestamp());
    return $diff;
}

Exit:

Total segundos: 20700
Total minutos: 345
Representación Horas,Minutos: 05:45
    
answered by 04.07.2018 в 16:03
-1

I recommend using a package called Carbon, this is your documentation link , it's the best I've seen to work with dates in php.

Example:

<code>
dt = Carbon::create(2012, 1, 31, 0);

//para sumar
echo $dt->addHours(24);                  // 2012-02-04 00:00:00
echo $dt->addHour();                     // 2012-02-04 01:00:00

//para restar
echo $dt->subHour();                     // 2012-02-04 00:00:00
echo $dt->subHours(24);                  // 2012-02-03 00:00:00
</code>
    
answered by 04.07.2018 в 16:36