954,597 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

math operations on time variables

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

dv1r
Light Poster
38 posts since Jan 2008
Reputation Points: 9
Solved Threads: 0
 
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.

diafol
Rhod Gilbert Fan (ardav)
Moderator
7,796 posts since Oct 2006
Reputation Points: 1,170
Solved Threads: 1,080
 

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

Biiim
Posting Whiz
387 posts since Oct 2011
Reputation Points: 93
Solved Threads: 55
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: