Average hours PHP

5

I want to add and take an average of a few hours.

$cadena = '00:09:00,00:09:00,00:09:00,00:09:00,00:09:00';
$arr = explode(",",$cadena);
$total = strtotime('00:00:00');

for($i = 0; $i<count($arr);$i++)
{
  $total = $total + strtotime($arr[$i]);
}

$total = $total / count($arr);
echo date('H:i:s',$total);

This brings me back 05:45:00 and I waited 00:09:00. What was the mistake: (

    
asked by Alberto Siurob 14.02.2017 в 01:31
source

3 answers

5

You could do something like this:

<?php

$cadena    = '00:09:00,00:09:00,00:09:00,00:09:00,00:09:00';
$arreglo   = explode(",", $cadena);
$resultado = 0;

foreach($arreglo AS $tiempo)
{
    $resultado += strtotime($tiempo) - strtotime("TODAY") . "\n";
}

$resultado = $resultado / count($arreglo);

echo gmdate("H:i:s", $resultado);

?>
  

Result:

     

00:09:00

    
answered by 14.02.2017 / 01:54
source
5

When you call strtotime without passing a date, it assumes the current date, and today's timestamp plus nine minutes is not the same as the timestamp of T = 0 plus nine minutes.

In particular, timestamp 0 occurred on December 31, 1969 at 9:00 p.m., so there is an implied lag of three hours in any strtotime. That has such strange consequences that

echo date('H:i:s',strtotime('00:00:00')+strtotime('00:09:00'));

Print

03:09:00

In your case, you are initializing the total with a non-zero value, so the average of that sum is meaningless.

Ivan Botero's solution solves your problem because it initializes the total explicitly to zero, and in each iteration of the loop removes the time delta between the current date and the initial timestamp of the universe.

    
answered by 14.02.2017 в 02:18
1

If you want to add here, this I hope it helps

<?php
$hora="14:00";//horas
$sumar=10;//minutos

$segundos_horaInicial=strtotime($hora);

$segundos_minutoAnadir=$sumar*60;//segundos

$total=date("H:i",$segundos_horaInicial+$segundos_minutoAnadir);

echo "<br>".$total;
?> 
    
answered by 14.02.2017 в 02:26