I am using Codeigniter and I want to do a subtraction on 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 time is 11:30 16:15
the result should be 4,85
but instead it shows me 5
. I hope I have explained myself 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);
The php diff function could help you .
The variable
$interval
becomes of type DateInterval ; if you want to operate with that variable, for example to add it to another date you can use the add function :DateTime
The point is that you need two valid objects to usediff
. From there you can get an itemDateInterval
withdiff
. You can then take advantage of the properties of that object to do whatever calculations you need.For example:
You have the output:
If you look inside your object
$dateInterval
you will see what it contains:We do one
var_dump($dateInterval);
and we will have:Suppose now you want to calculate how many minutes you have. You apply appropriate calculations to the properties
d, h, i
of the object (days, hours, minutes):You will have at the output:
Another way
Another thing you could do would be to get the timestamp of the two objects, subtract their value and do operations on it.
Let's see:
The output in this case would be:
Cumulative calculation using a loop
Let's assume your object is something like this.
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:
Departure:
I recommend you to use a package called Carbon, this is its documentation https://carbon.nesbot.com/docs/ , it is the best I have seen to work with dates in php.
Example:
while($query = mysqli_fetch_array($results)) {