I am saving the time in the database with a field of type time
. I am looping through an array of data and want to be able to sum it.
I have the following method:
<?php sumaHoras = 0; ?>
<?php while ($row = mysqli_fetch_assoc($result)) { ?>
$value_horario = $row['total'];
$parts = explode(':', $value_horario);
$resultado = ($parts[0] + ($parts[1]/6) / 10 . PHP_EOL);
$sumaHoras = $sumaHoras + $resultado;
} ?>
<?php echo $sumaHoras; ?>
If 3 hours come in my Array $row['total']
, the sum of those 00:30:00
+ 04:30:00
+ 01:00:00
gives me a result of 1.50
. should give me 7:00
or 07:00:00
.
I have been looking at some codes but none have worked for me.
I think the recommended thing is to perform the sum in seconds and then convert the total to the desired format, as follows:
according to what is understood of your needs and complemented with the help of @Oswuell, if you need to add several different hours, you can do it like this:
so you could add as many hours as you wanted....
I hope it works for you, tell us!
Try this, I use it and it works perfect for me
First you have to remove the ":" to transform them to integers.
Probably the cleanest and most elegant solution is to do the sum in the SQL code itself and get the result directly:
I start by converting the fields
TIME
to seconds (from the00:00:00
) using theTIME_TO_SEC()
. To the total sum of all the registers I do the inverse calculation (convert the elapsed seconds from the00:00:00
to hour) by means of the functionSEC_TO_TIME()
.Unlike the answer marked as correct, if the sum exceeds 24 hours, the result will be consistent in hours and will not start over from 0.
Your PHP code would be:
You can see an example online here .
I usually use the DateTime() object and create any date setting the time that interests me, then with the "modify" function I increase the time and extract it with "format".
In this example I only use hours but you can subtract whole dates, minutes and whatever you want quite easily without complex calculations.
You can combine the format as you are interested, create two dates if you see that it can increase or decrease more than 24h and then subtract them to see the difference in hours, etc.
It is interesting to consult the official documentation since it is perfectly explained:
http://php.net/manual/en/class.datetime.php
http://php.net/manual/en/datetime.modify.php