How can I add a given number of time in PHP?
Below is are three time variables I would like to add:
time1: \"00:02:00\"
time2: \"00:15:00\"
time3: \"
I've had several issues handling time in php.
The best way I've ever found it was this (and that way even if your calculation goes through 24 hours will not generate problems).
<?php
function time_to_sec($time) {
list($h, $m, $s) = explode (":", $time);
$seconds = 0;
$seconds += (intval($h) * 3600);
$seconds += (intval($m) * 60);
$seconds += (intval($s));
return $seconds;
}
function sec_to_time($sec) {
return sprintf('%02d:%02d:%02d', floor($sec / 3600), floor($sec / 60 % 60), floor($sec % 60));
}
$time1 = time_to_sec("00:02:00");
$time2 = time_to_sec("00:15:00");
$time3 = time_to_sec("00:08:00");
$total = $time1 + $time2 + $time3;
var_dump(sec_to_time($total));
?>
I hope I have helped.
You can use like this way. it will work.
$arr = [
'00:02:00',
'00:15:00',
'00:08:00'
];
$hour =0;$min=0;$sec=0;
foreach($arr as $a){
$time = explode(':',$a);
$sec +=$time[2];
$min +=$time[1];
$hour += $time[0];
}
echo sprintf('%02d',$hour).':'.sprintf('%02d',$min).':'.sprintf('%02d',$sec);
Thanks,
Try this one.This should do what you are looking for:
<?php
/**
* @param array $times
* @return string
*/
function sumOfDiffrentTime($times = array())
{
$minutes = '';
$seconds = '';
// loop through all the times array
foreach ($times as $time) {
list($hour, $minute, $second) = explode(':', $time);
$minutes += $hour * 60;
$minutes += $minute;
$seconds += (intval($second));
}
$hours = floor($minutes / 60);
$minutes -= $hours * 60;
// returns the formatted time
return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
}
$times = array();
$times[] = "00:02:00";
$times[] = "00:15:00";
$times[] = "00:08:00";
// pass your $times array to the function
echo sumOfDiffrentTime($times);
LIVE DEMO
Change from h
into H
.
h
=> 12-hour format of an hour with leading zeros
H
=> 24-hour format of an hour with leading zeros
Try
echo date('H:i:s', strtotime('00:02:00') + strtotime('00:15:00') + strtotime('00:08:00'));
Reference