We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,939 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

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

3
Contributors
2
Replies
1 Hour
Discussion Span
1 Year Ago
Last Updated
3
Views
dv1r
Light Poster
38 posts since Jan 2008
Reputation Points: 9
Solved Threads: 0
Skill Endorsements: 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
Keep Smiling
Moderator
10,647 posts since Oct 2006
Reputation Points: 1,628
Solved Threads: 1,509
Skill Endorsements: 57

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 Pro
504 posts since Oct 2011
Reputation Points: 104
Solved Threads: 83
Skill Endorsements: 7

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0601 seconds using 2.65MB