Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate elapsed time in php

Tags:

php

time

Hi All I'm trying to calculate elapsed time in php. The problem is not in php, it's with my mathematical skills. For instance: Time In: 11:35:20 (hh:mm:ss), now say the current time is: 12:00:45 (hh:mm:ss) then the time difference in my formula gives the output: 1:-34:25. It should actually be: 25:25

$d1=getdate(); $hournew=$d1['hours']; $minnew=$d1['minutes']; $secnew=$d1['seconds'];  $hourin = $_SESSION['h']; $secin = $_SESSION['s']; $minin = $_SESSION['m'];  $h1=$hournew-$hourin; $s1=$secnew-$secin; $m1=$minnew-$minin;  if($s1<0) {     $s1+=60; } if($s1>=(60-$secin)) {     $m1--;  } if($m1<0) {     $m1++; } echo $h1 . ":" . $m1 . ":" . $s1; 

Any help please?

EDIT

Sorry I probably had to add that the page refreshes every second to display the new elapsed time so I have to use my method above. My apologies for not explaining correctly.

like image 355
Wilest Avatar asked Oct 21 '11 13:10

Wilest


People also ask

How to calculate elapsed time php?

Find elapsed time in php using microtime. <? php $s = microtime(true); sleep(1); // 1 seconds $e = microtime(true); $timediff = $e - $s; echo 'Elapsed time (seconds): ' . sprintf('%0.2f', $timediff) .

How to calculate time in php?

There are two ways to calculate the total time from the array. Using strtotime() function: The strtotime() function is used to convert string into the time format. This functions returns the time in h:m:s format. Example 1: This example reads the values from the array and converts it into the time format.

How can add hours minutes and seconds in php?

php $time = "01:30:00"; list ($hr, $min, $sec) = explode(':',$time); $time = 0; $time = (((int)$hr) * 60 * 60) + (((int)$min) * 60) + ((int)$sec); echo $time; ?>


2 Answers

This will give you the number of seconds between start and end.

<?php  // microtime(true) returns the unix timestamp plus milliseconds as a float $starttime = microtime(true); /* do stuff here */ $endtime = microtime(true); $timediff = $endtime - $starttime;  ?> 

To display it clock-style afterwards, you'd do something like this:

<?php  // pass in the number of seconds elapsed to get hours:minutes:seconds returned function secondsToTime($s) {     $h = floor($s / 3600);     $s -= $h * 3600;     $m = floor($s / 60);     $s -= $m * 60;     return $h.':'.sprintf('%02d', $m).':'.sprintf('%02d', $s); }  ?> 

If you don't want to display the numbers after the decimal, just add round($s); to the beginning of the secondsToTime() function.

like image 184
WWW Avatar answered Oct 20 '22 00:10

WWW


Using PHP >= 5.3 you could use DateTime and its method DateTime::diff(), which returns a DateInterval object:

$first  = new DateTime( '11:35:20' ); $second = new DateTime( '12:00:45' );  $diff = $first->diff( $second );  echo $diff->format( '%H:%I:%S' ); // -> 00:25:25 
like image 39
Decent Dabbler Avatar answered Oct 20 '22 00:10

Decent Dabbler