Count total hours and minutes in PHP [duplicate] - php

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);
}

Related

Sum two centesimal times

I found this code but there is an error I can't found
function sum_time($tempo1, $tempo2) {
$times = array($tempo1, $tempo2);
$seconds = 0;
foreach ($times as $tempo)
{
list($hour, $minute, $second) = explode('.', $tempo);
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
// return "{$hours}:{$minutes}:{$seconds}";
return sprintf('%02d.%02d.%02d', $hours, $minutes, $seconds);
}
echo sum_time('3.0.00', '4.83.00');
the result is 08.23.00 instead of 7.83.00
Probably the problem is the code sums times in hh.mm.ss while I want to sum tims in hh.cc (hours.cents)
You can convert it to not use seconds but cents like this,
<?php
function sum_time($tempo1, $tempo2) {
$times = array($tempo1, $tempo2);
$hours = 0;
$cents = 0;
foreach ($times as $tempo)
{
list($hour, $cent) = explode('.', $tempo);
$hours += $hour;
$cents += $cent;
}
$hours += floor($cents / 100);
$cents = $cents % 100;
// return "{$hours}:{$cents}";
return sprintf('%02d.%02d', $hours, $cents);
}
echo sum_time('3.0', '4.83');

Sum(ADD) more than two time values in php

$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;

How to sum N number of time (HH:MM Format)?

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);
}

PHP Convert from strtotime into time

I need to add multiple time values as in Hours:mins, so I use
strtotime($value1) + strtotime($value2)
to add all of them, how do I put them back as hours:mins ?
cant use
date("h:i")
it only works if hours < 24.
I appreciate your help. Thanks
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
Try this :
function time_convert($s) {
$m = 0; $hr = 0; $td = "now";
if ($s > 59) {
$m = (int)($s/60);
$s = $s-($m*60); // sec left over
$td = "$m min";
}
if ($m > 59) {
$hr = (int)($m / 60);
$m = $m - ($hr*60); // min left over
$td = "$hr hr";
if ($hr > 1) {
$td .= "s";
}
if ($m > 0) {
$td .= ", $m min";
}
}
return $td;
}
And use it:
$time = (int) strtotime($v1) + strtotime($v2);
echo time_convert($time);
May it helps
The function strtotime() returns the time in seconds since January 1 1970 00:00:00 UTC. So adding the return value of this function might not do what you would expect.
Instead of using the date functions we can manipulate the string and perform some basic arithmetic operations:
<?php
$value1 = "12:44";
$value2 = "13:47";
$arr1 = explode(':', $value1);
$arr2 = explode(':', $value2);
$totalMinutes = (int)$arr1[0] * 60 + (int)$arr1[1] + (int)$arr2[0] * 60 + (int)$arr2[1];
$hours = (int) ($totalMinutes / 60);
$minutes = $totalMinutes % 60; // Modulus: remainder when dividing with 60
echo $hours . ':' . $minutes;
?>
Another way with DateTime
$dt1 = new DateTime($value1);
$dt2 = new DateTime($value2);
$interval = $dt1->diff($dt2);
echo $interval->format('%a day(s) %h hour(s) %i minute(s)') . '<br />';
echo ($interval->format('%a') * 24 + $interval->format('%h')) . ' hour(s) ';
echo $interval->format('%i minute(s)');

adding two time values of similar formats using php

i have two time values as give below
$time = 06:58:00;
$time2 = 00:40:00;
I am doing this for calculating the appointments and available time for a particular user
so i tried in this way
$max_date=abs(strtotime($time) + strtotime($time2));
but it is returning $max_date =2673452280
any suggestions pls
this code sample would take hour in $time and add the hour in $time2 to it
for example: time=06:58:00, time2=00:40:00, result = 07:38:00
$time = "06:58:00";
$time2 = "00:40:00";
$secs = strtotime($time2)-strtotime("00:00:00");
$result = date("H:i:s",strtotime($time)+$secs);
Use this function...
function sum_the_time($time1, $time2) {
$times = array($time1, $time2);
$seconds = 0;
foreach ($times as $time)
{
list($hour,$minute,$second) = explode(':', $time);
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
if($seconds < 9)
{
$seconds = "0".$seconds;
}
if($minutes < 9)
{
$minutes = "0".$minutes;
}
if($hours < 9)
{
$hours = "0".$hours;
}
return "{$hours}:{$minutes}:{$seconds}";
}
strtotime function takes full-date as an argument and valid format are as following:
http://www.php.net/manual/en/datetime.formats.php
You can see that in online PHP manual for the function at http://php.net/manual/en/function.strtotime.php
If you're build those time strings from a database before, you'd probably want to rebuild them to something like this:
$time = "00:06:58";
$time2 = "40 minutes";
$timestamp = strtotime($time." +".$time2);
$endTime = date("d.m.Y H:i:s", $timestamp);
Easiest way to add two times using php is :
1) Convert time from H:i:s (e.g. 08:15:40) format to seconds.
2) do the same for second time value ref:step 1
3) add converted values and store it php variable
4) Now convert total (which is in seconds) to H:i:s
and it works for me.
PHP Script:
$str_time ="08:04:40";
$str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $str_time);
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$hrs_old_seconds = $hours * 3600 + $minutes * 60 + $seconds;
$str_time ="02:10:22";
$str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $str_time);
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$hrs_toadd_seconds = $hours * 3600 + $minutes * 60 + $seconds;
$hrs_old_int1 = $hrs_old_seconds + $hrs_toadd_seconds;
echo $Total=gmdate("H:i:s", $hrs_old_int1);
Result= :10:15:02
Anudeep's solution was great for my use case, but I needed to be able to add negative times as well. Here's a slightly edited version of his code to take and return negative time strings ("-01:01:01" for example):
public static function sum_the_times($time1, $time2)
{
$times = array($time1, $time2);
$seconds = 0;
$negative = false;
foreach ($times as $time) {
list($hour,$minute,$second) = explode(':', $time);
if(substr($hour,0,1) == '-'){
$seconds -= substr($hour,1)*3600;
$seconds -= $minute*60;
$seconds -= $second;
} else {
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
}
if (substr($seconds, 0, 1) == '-') {
$negative = true;
$seconds = ($seconds * -1);
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
if ($seconds < 9) {
$seconds = "0".$seconds;
}
if ($minutes < 9) {
$minutes = "0".$minutes;
}
if ($hours < 9) {
$hours = "0".$hours;
}
return ($negative ? "-" : "")."{$hours}:{$minutes}:{$seconds}";
}
You can try this
$time = "04:00:00";
$time2 = "03:30:00";
$result = date("H:i:s",strtotime($time)+strtotime($time2));
echo $result;
It gives output 07:30:00 but it does not work sometime in different version of operating system. If you want to get sum of time then you can use this code
<?php
function CalculateTime($time1, $time2) {
$time1 = date('H:i:s',strtotime($time1));
$time2 = date('H:i:s',strtotime($time2));
$times = array($time1, $time2);
$seconds = 0;
foreach ($times as $time)
{
list($hour,$minute,$second) = explode(':', $time);
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
if($seconds < 9)
{
$seconds = "0".$seconds;
}
if($minutes < 9)
{
$minutes = "0".$minutes;
}
if($hours < 9)
{
$hours = "0".$hours;
}
return "{$hours}:{$minutes}:{$seconds}";
}
$time1= '23:32:05';
$time2 = '01:29';
echo CalculateTime($time1,$time2);
?>
In the second code, you can send time in hour:minutes or hours:minutes:seconds. This code accept both format because it convert time automatically
Here's a version that will cater for over 24 hours and doesn't use strtotime:
$time0 = "24:01:02";
$time1 = "01:02:03";
$matches0 = explode(':',$time0); // split up the string
$matches1 = explode(':',$time1);
$sec0 = $matches0[0]*60*60+$matches0[1]*60+$matches0[2];
$sec1 = $sec0+ $matches1[0]*3600+$matches1[1]*60+$matches1[2]; // get total seconds
$h = intval(($sec1)/3600);
$m = intval(($sec1-$h*3600)/60);
$s = $sec1-$h*3600-$m*60;
echo $str = str_pad($h, 2, '0', STR_PAD_LEFT).':'.str_pad($m, 2, '0', STR_PAD_LEFT).':'.str_pad($s, 2, '0', STR_PAD_LEFT);

Categories