I have a list of video segment durations I need to add up to get the total duration.
The series is like this:
0:33
4:30
6:03
2:10
...etc
I need to add up the minutes and seconds to get a total video duration.
Here's the modified function of my accepted answer:
function getTotalDuration ($durations) {
$total = 0;
foreach ($durations as $duration) {
$duration = explode(':',$duration);
$total += $duration[0] * 60;
$total += $duration[1];
}
$mins = floor($total / 60);
$secs = str_pad ( $total % 60, '2', '0', STR_PAD_LEFT);
return $mins.':'.$secs;
}
Just made sure the output looks correct.
Give this code a shot:
function getTotalDuration ($durations) {
$total = 0;
foreach ($durations as $duration) {
$duration = explode(':',$duration);
$total += $duration[0] * 60;
$total += $duration[1];
}
$mins = $total / 60;
$secs = $total % 60;
return $mins.':'.$secs;
}
This stores the result in $seconds:
$seconds = 0;
foreach ($times as $time):
list($m,$s) = explode(':',$time);
$seconds += $s + 60*$m;
endforeach;
Convert all times to seconds, add them as integers, convert the sum back to minutes and seconds?
Related
I am using the following sample code to calculate sum of two different time values. Now I want to get the sum of N number of time values.
// numbers for testing
$o="12:59";
$p="0:58";
// display for testing
echo "$o<br />";
echo "$p<br />";
echo AddPlayTime($o,$p);
// FUNCTION - ADD HOURS and MINUTES
function AddPlayTime ($oldPlayTime, $PlayTimeToAdd) {
$old=explode(":",$oldPlayTime);
$play=explode(":",$PlayTimeToAdd);
$hours=$old[0]+$play[0];
$minutes=$old[1]+$play[1];
if($minutes > 59){
$minutes=$minutes-60;
$hours++;
}
if($minutes < 10){
$minutes = "0".$minutes;
}
if($minutes == 0){
$minutes = "00";
}
$sum=$hours.":".$minutes;
return $sum;
}
this should do what you are looking for:
$times is the array of times and you can add how many time you want
$times = array();
$times[] = "12:59";
$times[] = "0:58";
$times[] = "0:02";
// pass the array to the function
echo AddPlayTime($times);
function AddPlayTime($times) {
$minutes = 0; //declare minutes either it gives Notice: Undefined variable
// loop throught all the times
foreach ($times as $time) {
list($hour, $minute) = explode(':', $time);
$minutes += $hour * 60;
$minutes += $minute;
}
$hours = floor($minutes / 60);
$minutes -= $hours * 60;
// returns the time already formatted
return sprintf('%02d:%02d', $hours, $minutes);
}
EDIT
I edited the code with the right names of the variables. It is more correct now.
hope this helps :-)
Here is an function that will sum all your time values in format HH:MM:
function sum_time() {
$i = 0;
foreach (func_get_args() as $time) {
sscanf($time, '%d:%d', $hour, $min);
$i += $hour * 60 + $min;
}
if ($h = floor($i / 60)) {
$i %= 60;
}
return sprintf('%02d:%02d', $h, $i);
}
// use example
echo sum_time('01:05', '00:02', '05:59'); # 07:06
demo
function sumarHoras($acumuladoTime, $nuevoTime){
//Se esperan parametros asÃ:
//$acumuladoTime="02:45";
//$nuevoTime="04:36";
//echo "Hora acumulada: $acumuladoTime"."<br>";
//echo "Nuevo tiempo acumulado: $nuevoTime"."<br>";
/*Tiempo acumulado*/
$myArrayAcumuladoTime=explode(":", $acumuladoTime);
$hrsAcumuladoTime=$myArrayAcumuladoTime[0];
$minsAcumuladoTime=$myArrayAcumuladoTime[1];
/*Nuevo Time*/
$myArrayNewTime=explode(":", $nuevoTime);
$hraNewTime=$myArrayNewTime[0];
$minNewTime=$myArrayNewTime[1];
/*Calculo*/
$sumHrs=$hrsAcumuladoTime+$hraNewTime;
$sumMins=$minsAcumuladoTime+$minNewTime;
/*Si se pasan los MINUTOS*/
if($sumMins>59){
/*Quitamos hora para dejarlo en minutos y se la sumamos a la de horas*/
$sumMins-=60;
$sumHrs+=1;
}
// echo "Total hrs agregadas: $sumHrs:$sumMins"."<br>";
return "$sumHrs:$sumMins";
}
This is the best way:
<?php
function CalculateTime($times) {
$i = 0;
foreach ($times as $time) {
sscanf($time, '%d:%d', $hour, $min);
$i += $hour * 60 + $min;
}
if($h = floor($i / 60)) {
$i %= 60;
}
return sprintf('%02d:%02d', $h, $i);
}
$date[] = '02:32';
$date[] = '01:29';
echo CalculateTime($date);
?>
Laravel Framework (PHP language)
$chores = ChoresTime::where('family_id', $family->id)->get();
$total = [];
foreach ($chores as $key => $value) {
$total[] = $value->time;
}
$total = CalculateTime($chores);
return response()->json([
'status' => 1,
'message' => 'Total Time',
'data' => [],
'total' => $total
], ok());
Answer:
{
"status": 1,
"message": "Family Total Chores Time",
"data": [],
"total": "14:22"
}
I have extended the above sum_time function to seconds:
function sum_time()
{
$hh = 0;
$mm = 0;
$ss = 0;
foreach (func_get_args() as $time)
{
sscanf( $time, '%d:%d:%d', $hours, $mins, $secs);
$hh += $hours;
$mm += $mins;
$ss += $secs;
}
$mm += floor( $ss / 60 ); $ss = $ss % 60;
$hh += floor( $mm / 60 ); $mm = $mm % 60;
return sprintf('%02d:%02d:%02d', $hh, $mm, $ss);
}
I would like to know how to subtract two variables that represent minutes in PHP
For example I have two minute variables
$minutes1 = 20;
$minutes2 = 45;
$totalMinutes = $minutes1 -$minutes2;
//output should be 35 as $totalMinutes
An example would be
$time1 = "2:20";
$time2 = "3:45";
$finalTime = $time2 - $time1
//final time = 1:25
I am only interested in the minutes and not the hours
I bet that there's some cleaner way, but this seem to do what you're asking for.
$m1 = 20;
$m2 = 45;
$diff = $m1 - $m2;
echo $diff >= 0 ? $diff : $diff + 60;
This returns 35. Demo: https://3v4l.org/WaC8r
EDIT: Based on comments I have a better understanding of what you are asking for and have written this function.
function subtractMinutes($start, $sub) {
$res = $start;
while ($sub > 0) {
if ($sub >= 60) {
$sub -= 60;
continue;
}
if ($res >= $sub) {
$res -= $sub;
break;
}
if ($sub > $res) {
$sub -= $res + 1;
$res = 59;
continue;
}
$sub -= $res;
$res = 0;
}
return $res;
}
var_dump(subtractMinutes(20, 45)); //35
var_dump(subtractMinutes(20, 60)); //20
var_dump(subtractMinutes(20, 120)); //20
var_dump(subtractMinutes(20, 121)); //19
var_dump(subtractMinutes(40, 40)); //0
var_dump(subtractMinutes(59, 58)); //1
Please note that this answer attempts to provide a general solution.
If you only need to subtract a couple of times by all means, just
check with 60.
I would insist on suggesting you should be using decimals for all operations, and only turn into the correct format when outputting the result on a page. I believe it is safer to do calculations this way, instead of relying on you remembering to add/subtract 60 every time.
Examples:
$single_minute = 1.66;
$twenty_minutes = 20*1.66 = 33.2;
$sixty_minutes = 60*1.66 = 99.6;
When outputing:
$out_twenty = round(33.2/1.66);
$out_sixty = round(99.6/1.66);
You can use helper constants:
define("MINUTE", 1.66);
//You want to calculate 34 minutes
$thirtyfour_minutes = MINUTE * 34;
//You want to output 34 minutes
echo round($thirtyfour_minutes);
$time = array("18:10:00", "23:10:12", "10:05:00");
How to get the total time from this array. I need output like 51:25:12, Please help me
Try this short code:
It fill up your all case. Like as case:$a=array("18:30:00", "23:30:12", "10:05:00");.
function sum_time($array) {
$i = 0;
foreach ($array as $time) {
sscanf($time, '%d:%d:%d', $hour, $min,$sec);
$i += ($hour * 60 + $min)*60+$sec;
}
if ($h = floor($i / 3600)) {
$i %= 3600;
if ($m = floor($i / 60)) {
$i %= 60;
}
}
return sprintf('%02d:%02d:%02d', $h, $m,$i);
}
$a=array("18:30:00", "23:30:12", "10:05:00");
echo sum_time($a);
<?php
$time = array("18:10:00", "23:10:12", "10:05:00");
$hours=0;
$min=0;
$sec=0;
foreach($time as $time_array)
{
$time_exp=explode(':',$time_array);
$hours=$hours+$time_exp[0];
$min=$min+$time_exp[1];
$sec=$sec+$time_exp[2];
}
$time_output='';
$time_output=$hours.':'.$min.':'.$sec;
echo $time_output;
?>
// sample data
$time = array("18:50:00", "23:10:12", "10:05:00");
//variable initialization
$seconds = $mins = $hours = array();
//loop through all sample data items
foreach($time as $tk => $tv) {
//explode each item with seperator
$tv_parts = explode(":", $tv);
$seconds[] = $tv_parts['2'];
$mins[] = $tv_parts['1'];
$hours[] = $tv_parts['0'];
}
//add up all items respectively
$ts = array_sum($seconds);
$tm = array_sum($mins);
$th = array_sum($hours);
//adjust seconds if they are more than 59
if($ts > 59) {
$ts = $ts % 60;
$tm = $tm + floor($ts / 60);
}
//adjust minutes if they are more than 59
if($tm > 59) {
$tm = $tm % 60;
$th = $th + floor($tm / 60);
}
//padding for adjusting it to two digits when sum is below 10
$th = str_pad($th, 2, "0", STR_PAD_LEFT);
$tm = str_pad($tm, 2, "0", STR_PAD_LEFT);
$ts = str_pad($ts, 2, "0", STR_PAD_LEFT);
//final output
echo "$th:$tm:$ts";
You can refer more details about array_sum, floor and str_pad on official documentation site for PHP.
Easiest way to do this is as follows:
$time = array("18:10:00", "23:10:12", "10:05:00");
$sum="00:00:00";
$sum_new = explode(':',$sum);
foreach ($time as $t)
{
$time_new = explode(':',$t);
$sum_new[0]=$sum_new[0]+$time_new[0];
$sum_new[1]=$sum_new[1]+$time_new[1];
$sum_new[2]=$sum_new[2]+$time_new[2];
}
$sum = implode(':',$sum_new);
echo $sum;
First explode current date string via : and than just sum up parts. Don't forget to fix overflow of time parts:
function sum($times) {
$total = array(
'h' => 0,
'm' => 0,
's' => 0,
);
foreach ($times as $t) {
$timeArray = explode(":", $t);
$total['h'] += $timeArray[0];
$total['m'] += $timeArray[1];
$total['s'] += $timeArray[2];
}
if ($total['s'] >= 60) {
$total['m'] += $total['s'] % 60;
$intpart = floor($total['s']);
$total['s'] = $total['s'] - $intpart;
}
if ($total['m'] >= 60) {
$total['h'] += $total['m'] % 60;
$intpart = floor($total['m']);
$total['m'] = $total['m'] - $intpart;
}
return $total;
}
$totals = sum(array("18:10:00", "23:10:12", "10:05:00"));
echo implode(':', $totals);
Try this:
<?php
$time = array("18:10:00", "23:10:12", "10:05:00");
$seconds = 0;
foreach($time as $t)
{
$timeArr = array_reverse(explode(":", $t));
foreach ($timeArr as $key => $value)
{
if ($key > 2) break;
$seconds += pow(60, $key) * $value;
}
}
$hours = floor($seconds / 3600);
$mins = floor(($seconds - ($hours*3600)) / 60);
$secs = floor($seconds % 60);
echo $hours.':'.$mins.':'.$secs;
I have some total sums of hours and need to calculate the average. For example, my total hour value is 2452:43:44 (H:m:s) and the total count is 15. I would like to get the average time in the same format, that is hours:minutes:seconds. How can we do it in PHP ?
function average_time($total, $count, $rounding = 0) {
$total = explode(":", strval($total));
if (count($total) !== 3) return false;
$sum = $total[0]*60*60 + $total[1]*60 + $total[2];
$average = $sum/(float)$count;
$hours = floor($average/3600);
$minutes = floor(fmod($average,3600)/60);
$seconds = number_format(fmod(fmod($average,3600),60),(int)$rounding);
return $hours.":".$minutes.":".$seconds;
}
echo average_time("2452:43:44", 15); // prints "163:30:55"
echo average_time("2452:43:44", 15, 2); // prints "163:30:54.93"
Close to Antony's solution, but with array of hours given:
$time = array (
'2452:43:44',
'452:43:44',
'242:43:44',
'252:43:44',
'2:43:44'
);
$seconds = 0;
foreach($time as $hours) {
$exp = explode(':', strval($hours));
$seconds += $exp[0]*60*60 + $exp[1]*60 + $exp[2];
}
$average = $seconds/sizeof( $time );
echo floor($average/3600).':'.floor(($average%3600)/60).':'.($average%3600)%60;
$totalhourandmunite+=str_replace(":",'',$date);
strtoheur(round($totalhourandmunite/$nbdate,0));
function strtoheur($temp)
{
if(strlen($temp)==1) return $temp;
if(strlen($temp)==2)
$temp=$temp."00";
if(strlen($temp)==3)
$temp="0".$temp;
$temp=str_split($temp);
$heure=$temp["0"].$temp["1"];
$min=$temp["2"].$temp["3"];
if($min/60>1)
{
$min=$min%60;
$heure++;
}
if($min<10 && strlen($min)==1)
$min="0".$min;
if($heure>23)
{
$heure=$heure%24;
}
$temp=$heure.":".$min;
return $temp;
}
The best way would be to change the total hour value in seconds.
Divide it by total count value. What you will get is average in seconds.
Convert average back in H:m:s format.
On our site, we have a lot of swimming times that we would like to convert to seconds. i.e. 1:23:33.03 or 58:22.43. Is there a PHP function that can do this? A MySQL function?
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_time-to-sec
mysql> SELECT TIME_TO_SEC('22:23:00');
-> 80580
mysql> SELECT TIME_TO_SEC('00:39:38');
-> 2378
function time2seconds($time='00:00:00')
{
list($hours, $mins, $secs) = explode(':', $time);
return ($hours * 3600 ) + ($mins * 60 ) + $secs;
}
From here.
MySQL also has TIME_TO_SEC()
so if mysql without fractions not appropriate solution - here is another mine
$time = '1:23:33.03';
$parts = explode(':', $time);
$seconds = 0;
foreach ($parts as $i => $val) {
$seconds += $val * pow(60, 2 - $i);
}
echo $seconds;
Use the following program for converting time to seconds in php.
<?php
function time_to_sec($time) {
$hours = substr($time, 0, -6);
$minutes = substr($time, -5, 2);
$seconds = substr($time, -2);
return $hours * 3600 + $minutes * 60 + $seconds;
}
$result=time_to_sec('12:25:59');
echo $result;
?>
$current_time_in_seconds="01:21:44.24";
list($hours, $minutes, $seconds) = explode(":", $current_time_in_seconds);
$current_time_in_seconds=$hours*3600+$minutes*60+$seconds;
will get from
01:21:44.24
to
4904.24
Strtotime is what you need. You get a Unix timestamp which in this case would be the number of seconds.
I am a little confused but I think that you mean. 1 hour, 23 minuts and 23.03 seconds.
this is not difficult to do. I made this PHP function that does that. My php server doesn't want to start up, so I couldn't test it, but I think it should work.
function ConvertTimeToSeconds($T)
{
$exp = explode(":",$T);
$c = count($exp);
$r = 0;
if ($c == 2)
{
$r = (((int)$exp[0]) * 60) + ((int)$exp[1]);
}else{
$r = (((int)$exp[0]) * 3600) + (((int)$exp[1]) * 60) + ((int)$exp[2]);
}
return $r;
}
ConvertTimeToSeconds("1:23:33.03");