i know this is a stupid question but i just don't know :\

if i have 2 time variables

a = 00:00:12 and b = 00:00:05

how would i add them together to make

c = 00:00:17 ?

i get the data from the database in this format and when i try a simple

c=a+b;

i get

00

thank you in advance

Recommended Answers

All 2 Replies

Member Avatar for diafol
function add_time($time1,$time2){
  $t1 = explode(":",$time1);
  $t2 = explode(":",$time2);
  for($x=0;$x<3;$x++){
	$totals[] = intval($t1[$x]) + intval($t2[$x]);	  
  }
  $minsfromsecs = floor($totals[2]/60);
  $secs = str_pad($totals[2] - $minsfromsecs * 60,2, '0', STR_PAD_LEFT);
  $mins = $totals[1] + $minsfromsecs;
  $hoursfrommins = floor($mins/60);
  $mins = str_pad($mins - $hoursfrommins * 60,2, '0', STR_PAD_LEFT);
  $hours = str_pad($totals[0] + $hoursfrommins,2, '0', STR_PAD_LEFT);
  return "$hours:$mins:$secs"; 
}

$start = '00:00:57';
$finish = '00:59:05';

echo add_time($start,$finish);

works for me. It's a rush job, no doubt that it could be optimized though. Maybe better time functions I don't know about / forgot too.

not specific dates?

i would use strtok to pull out the hours, mins and seconds then compare them how you want

function timeToSeconds($timeStr){
$hours = strtok(':',$timeStr);
$mins = strtok(':');
$secs = strtok(':');
if($hours > 0){
$secs += ($hours*3600);
}
if($mins > 0){
$secs += ($mins*60);
}
return $secs;
}

$a = "00:00:05";
$b = "00:00:12";

$as = timeToSeconds($a);
$bs = timeToSeconds($b);

echo $as+$bs;//17

not tested it, i could imagine it might complain about the vars being strings

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.