Calculate elapsed time in php - php

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.

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.

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

Keep track of your time using the 'time()' function.
You can later convert 'time()' to other formats.
$_SESSION['start_time'] = time();
$end_time = time();
$end_time - $_SESSION['start_time'] = 65 seconds (divide by 60 to get minutes)
And then you can compare that to another value later on.
Use microtime if you need millisecond detail.

You can implement the solutions shown, but I'm fond of using the phptimer class (or others, this wheel has been invented a few times). The advantage is that you can usually define the timer to be active or not, thereby permitting you to leave the timer calls in your code for later reference without re-keying all the time points.

For high resolution time, try using monotonic clock: hrtime
<?php
$time = -hrtime(true);
sleep(5);
$end = sprintf('%f', $time += hrtime(true));
?>
Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

Related

PHP Get last increment of five minutes [duplicate]

This question already has answers here:
Subtract time in PHP
(3 answers)
Closed 3 years ago.
I am looking to get the previous increment of five minutes from the current time...
Lets say that the current time is 12:07pm UTC
I want to put into a variable 12:05pm UTC
What would be an easy way of going about this?
You can do this with the DateTime class (https://3v4l.org/7aqMH):
<?php
$date = new DateTime('12:07 UTC');
$minutes = (int) $date->format('i');
$rounded = round($minutes / 5) * 5;
$date->setTime($date->format('H'), $rounded, $date->format('s'));
or more concisely:
<?php
$date = new DateTime('12:07 UTC');
$date->setTime(
$date->format('H'),
round($date->format('i') / 5) * 5,
$date->format('s')
);
There's nothing built in that allows you to retrieve 'increments' however you can calculate it with minimal code. The use of modulo here allows you to figure out how far past the most recent 5 minute mark is. It will never be greater than 5 minutes (300 seconds) and can always be subtracted safely to take you back to the time you want.
$now = time();
echo $now . PHP_EOL;
$five_minutes = 60*5; // 300
$offset = $now % $five_minutes;
$five_block = $now - $offset;
echo date('Y-m-d H:i:s', $five_block);
First you will want to extract the minutes from their stored variable. Then mathematically this is simple by applying division and the floor function. To do this you can first divide by five using intdiv(numerator, denominator) which will remove any trailing decimal points and then multiply by five again to get your desired value at an increment of five.
Get the current time using time() :
$min = 300
$currentTime = time();
$mod = $currentTime % $min;
$res = $currentTime - $mod;
finalResult = date('Y-m-d H:i:s', $res);

how to divide hours in php?

I have tried to search for the answer for my problem for quite a while now and I did not solve it yet. I am new to PHP.
Problem.
Divide 2:00 by 2 (hr/2) = 1:00 //format h:i
Thanks.
I think the safest way is to convert to seconds and use date to display it.
$time ="3:00";
list($hours, $minutes) = explode(":", $time);
$minutes += $hours*60;
$seconds = $minutes*60;
date_default_timezone_set ("UTC"); // makes sure there is no DST or timezone added to result
echo "new time: " . date("h:i", $seconds/2); // 01:30
Your question states "h:i" format yet it's written as "1:00".
To get 1:00 you need to use format "G:i".
https://3v4l.org/4MjVQ
For the record, dividing time is trivial in any programming/scripting language. Because if we are talking about a timestamp, dividing that would make no sense, because a timestamp is a particular point on the line of chronology.
Time duration in the other hand, could be divided. However, I am not so sure if php's API has any implementation for time duration handling. Still you can go on for your own customized implementation to handle time intervals. It would be something like follows.
<?php
#We need at least two timestamps to get a duration
$time1 = new DateTime("2018-4-23 10:00:00");
$time2 = new DateTime("2018-4-23 11:00:00");
$durationInSeconds = ($time2->getTimestamp()) - ($time1->getTimestamp()); //Get the interval in seconds
#echo $durationInSeconds; // Gives you 3600 seconds
# Now you can divide these seconds into anything you prefer.
# Let's say I want two intervals. This means, I have to go for the timestamp in between the two. I could do that by simply adding half the amount of seconds
$halfDurationInSeconds = $durationInSeconds / 2;
$time1->add(new DateInterval("PT".$halfDurationInSeconds."S")); // adds 1800 secs
echo $time1->format('Y-m-d H:i:s');
Its very simple. Use strtotime
$your_time = "12:00";
date_default_timezone_set ("UTC");
$secs = strtotime($your_time ) - strtotime("00:00:00");
echo date("H:i:s",$secs / 2);
I think we can also use multiplication here. Thanks for the suggestions above. It really did help me a lot. This is my modified code for the suggestions above.
function multiplyTime ($multiple, $prescribeWorkingHrs) {
list($hours, $minutes) = explode(":", $prescribeWorkingHrs);
$minutes += $hours*60;
$seconds = $minutes*60;
$product = $seconds * $multiple;
return date("h:i", $product);
}
Results:
multiplyTime(0.75, "8:00") = "6:00"
multiplyTime(0.5, "8:00") = "4:00"
multiplyTime(0.25, "8:00") = "2:00"
Hope this will help too. Thanks

Multiple hour by a number

I have something like that for example: 01:06:22 this represents 1hour, 6minutes and 22seconds. I want to take that, and multiple it by 6 and add it to some other hour such as 04:23 which is 4AM and 23Minutes not 4hours and 23 minutes.
Basically, as a result I expect that:
01:06:22
* 6 = 6hours 38minutes canceling the remaining seconds which are 12 in this case
Now, I want to take that and append it to other hour, 04:23 in this case, so the result would be:
11:01.
I have no clue how to start and do it, unfortunately.
Any help is appriciated!
Clarifications
The time that I have to multiple by 6 will never exceed 2 hours.
All the times are in the same format.
With DateTime it is simple:
$time = '01:06:22';
$dateSeconds = new DateTime("1970-01-01 $time UTC");
$seconds = $dateSeconds->getTimestamp() * 6;
$interval = new DateInterval('PT'.$seconds.'S');
$date = new DateTime('1970-01-01 04:23:00 UTC');
$date->add($interval);
echo $date->format('H:i:s');
Other solution with strtotime and gmdate. (Similar to Suresh but working):
$date = strtotime('1970-01-01 01:06:22 UTC');
$add = strtotime('1970-01-01 04:23:00 UTC');
$date = (($date*6)+$add);
echo gmdate('H:i:s', $date);
This is a solution if you want to implement it yourself.
The thing about timecode is that it can become really heavy with the if the if conditions etc if you don't do it right.
The best Way I thought of to deal with this is to convert everything to second.
so 01:06:22 would become:
numberOfSecond = 22 + 06 * 60 + 01 * 60 * 60
How to get the 22, 06 etc from the String? You can use Regex.
What you will need:
a function to extract the different values (hours, minute, second)
a function to convert the timecode into second
a function to convert back into timecode
the functions to multiply, add etc...
You might want to create a class for it.
You can try like this:
$date = strtotime('01:06:22');
$add = strtotime('00:04:23');
$date = ($date*6)+$add;
echo date('H:i:s', $date);
Note: Code is not tested.
First of all you want to multiply a time span by a factor. The easiest way to do this is to convert the span to seconds and do a straight multiply:
$date =DateTime::createFromFormat('!H:i:s', '01:06:22', new DateTimeZone('UTC'));
$seconds = $date->getTimestamp();
This code works by pretending that the time is a moment during the Unix epoch start so that it can then get the number of seconds elapsed since the epoch (the timestamp). That number is equal to the duration of the time span in seconds. However, it is vitally important that the input is interpreted as UTC time and not as something in your local time zone.
An equivalent way of doing things (as long as the input is in the correct format) which is lower-tech but perhaps less prone to bugs would be
list($h, $m, $s) = explode(':', '01:06:22');
$seconds = $h * 3600 + $m * 60 + $s;
Now the multiplication:
$seconds = $seconds * 6;
If you want to only keep whole minutes from the time you can do so at this stage:
$seconds = $seconds - $seconds % 60;
The final step of adding the result to a given "time" is not clearly specified yet -- does the reference time contain date information? What happens if adding to it goes over 24 hours?
Self explanatory :
$initialTime = '01:06:22';
$timeToAdd = '04:23';
$initialTimeExploded = explode( ':' ,$initialTime );
$initialTimeInMintues = ( $initialTimeExploded[0] * 60 ) + $initialTimeExploded[1];
$initialTimeInMintuesMultipliedBySix = $initialTimeInMintues * 6;
$timeToAddExploded = explode( ':' ,$timeToAdd );
$timeToAddExplodedInMintues = ( $timeToAddExploded[0] * 60 ) + $timeToAddExploded[1];
$newTimeInMinutes = $initialTimeInMintuesMultipliedBySix + $timeToAddExplodedInMintues;
$newTime = floor( $newTimeInMinutes / 60 ) .':' .($newTimeInMinutes % 60);
echo $newTime;
Result :
10:59

Adding hours in PHP

I figured this would be a very simple problem but I haven't found a solution anywhere.
I am creating a scheduling program in PHP and mySQL. The shifts have a startTime and endTime, each of which are stored as TIME in mySQL.
I want to add up the total hours for an employee during the week, so I tried:
$shifts = [...] //shifts for the week
$totalTime = 0; //I've also tried "0:0:0" and strtotime("0:00:00");
for($d = 0; $d < 7; $d++){
$start = strtotime($shift_types[$shifts[$d]]['ShiftType']['start_time']);
$end = strtotime($shift_types[$shifts[$d]]['ShiftType']['end_time']);
echo date("g:ia", $start) . ' / ' . date("g:i a", $end);
$totalTime += ($end-$start);
}
}
The problem with this, is that $totalTime doesn't come out to any reasonable number. I think this is because PHP is treating $totalTime as a timestamp since 1970, which would result in something completely different. All I really want is a value of net hours, it doesn't need to have any date-ish values associated with it.
I should mention that I'm displaying the total time with
echo date("g:i", $totalTime);
When it is run with a start of 9:30:00 and an end of 16:15:00, it displays "1:45".
When the total time isn't touched (because there are no shifts), it displays "7:00".
strtotime returns a Unix timestamp, the number of seconds since the epoch represented by that time. So working with seconds (and starting $totalTime at zero) is the correct approach. If you want the number of hours, you need to: $totalTime = $totalTime / (60 * 60); after your loop (divide by 3600 seconds / hour).
I think this does what you want to do:
$t1 = strtotime("2013-01-01 00:00:00");
$t2 = strtotime("2013-01-15 00:00:00");
echo round(($t2-$t1)/3600) ." hours". PHP_EOL;
Or you could look to use two DateTime objects and the diff() method as described in my blog post http://webmonkeyuk.wordpress.com/2011/05/04/working-with-date-and-time-in-php/

How to find time difference between 2 time vars greater than 24 hours

I need to find how much time is between to time values (their difference) which are over 24:00:00.
For example: how can I calculate the difference between 42:00:00 and 37:30:00?
Using strtotime, strptotime, etc is useless since they cannot go over 23:59:59 ....
$a_split = explode(":", "42:00:00");
$b_split = explode(":", "37:30:00");
$a_stamp = mktime($a_split[0], $a_split[1], $a_split[2]);
$b_stamp = mktime($b_split[0], $b_split[1], $b_split[2]);
if($a_stamp > $b_stamp)
{
$diff = $a_stamp - $b_stamp;
}else{
$diff = $b_stamp - $a_stamp;
}
echo "difference in time (seconds): " . $diff;
then use date() to convert seconds to HH:MM:SS if you want.
Date/Time variables and functions are not appropriate here as you're not storing time, but instead a time span of (I assume) hours, minutes, and seconds.
Likely your best solution is going to be to split each time span into their integer components, convert to a single unit (for instance, seconds), subtract them from each other, then re-build an output time span that fits with your application.
I havent tested this, but this might do what you want:
function timediff($time1, $time2) {
list($h,$m,$s) = explode(":",$time1);
$t1 = $h * 3600 + $m * 60 + $s;
list($h2,$m2,$s2) = explode(":",$time2);
$seconds = ($h2 * 3600 + $m2 * 60 + $s2) - $t1;
return sprintf("%02d:%02d:%02d",floor($seconds/3600),floor($seconds/60)%60,$seconds % 60);
}

Categories