1,105,538 Community Members

math operations on time variables

Member Avatar
dv1r
Light Poster
38 posts since Jan 2008
Reputation Points: -1 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Member Avatar
diafol
Where are my eyes?
12,977 posts since Oct 2006
Reputation Points: 1,821 [?]
Q&As Helped to Solve: 1,848 [?]
Skill Endorsements: 92 [?]
Moderator
Featured
Sponsor
 
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.

Member Avatar
Biiim
Posting Pro
504 posts since Oct 2011
Reputation Points: 85 [?]
Q&As Helped to Solve: 86 [?]
Skill Endorsements: 9 [?]
 
0
 

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

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: