How to get time average - php

I have a time calculations problem in getting average.
I have this summed up call time 06:03:05 and I want to get an average with 175 calls.
date_default_timezone_set('America/Chicago');
$ts = strtotime("06:03:05");
echo date("H:i:s", $ts/175);
I get:
12:26:25
I'm not even sure why I come up with this very huge time average. Am I doing this right? Please help.

The problem there is that your strtotime call, not having a date component, is defaulting to the current date. So the $ts is a much much larger number than just the sum of the time parts; it includes the date parts as well.
I would avoid using the time functions like that. It's simple enough to calculate the number of seconds based on the hours, minutes and seconds. Once you have that, you can use date() to echo the formatted time like you do there.
Try something more like this:
function getTimeAverage($hours, $minutes, $seconds, $division) {
$seconds += ($hours * 3600) + ($minutes * 60);
return $seconds / $division;
}
$average = getTimeAverage(6, 3, 5, 175);
echo gmdate("H:i:s", $average);

One easy way which only works up to 24 hours. Else take Atlis approach and search also for a way to convert seconds to date.
$time = '06:03:05';
$seconds = strtotime("1970-01-01 $time UTC");
$average = $seconds/175;
echo gmdate('H:i:s', $average);

Related

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

Converting a Total Time to Seconds

I'm totalling up time like so.
$totalTimeDiff = new DateTime("#0");
foreach($dbrecords as $row)
{
$timeDiff = date_diff( ... two datetimes from my database ... )
$totalTimeDiff->add($timeDiff);
}
So $totalTimeDiff is a DateTime object with the sum of all of the time differences added together (so a sum of all of the durations). How can I get the total time in seconds?
Why not keep it simple?
$totalseconds=0;
foreach($dbrecords as $row)
$totalseconds+=(UNIX_TIMESTAMP(second_datetime)-UNIX_TIMESTAMP(first_datetime));
use strtotime function
echo strtotime('01:00:00') - strtotime('TODAY');
$totalTimeDiff->format('U');
Taking moonwave99's advice, I used DateInterval (can't remember why I went with DateTime for that in the first place, possibly a workaround for something at another stage of the project) and computed the seconds by adding each value to the total after converting it to seconds (converting hours and minutes to seconds and summing them up). I did this by using the DateInterval class's seconds property as well as the following function to convert a DateInterval to seconds (Note: only accounted for days, hours, minutes, and seconds for my specific case as there's no chance the amount will exceed one month):
function convertDateIntervalToSeconds($dateInterval)
{
$days = $dateInterval->d * 24 * 60 * 60;
$hours = $dateInterval->h * 60 * 60;
$minutes = $dateInterval->i * 60;
$seconds = $dateInterval->s;
return $hours + $minutes + $seconds;
}

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);
}

Subtract time in PHP

I have been looking for an answer for a few hours now, but I can't find one.
I'm writing a simple script. The user sets their work start and end time. So, for example, somebody is working from 8:00 to 16:00.
How can I subtract this time to see how long the person has been working?
I was experimenting with strtotime(); but without success...
A bit nicer is the following:
$a = new DateTime('08:00');
$b = new DateTime('16:00');
$interval = $a->diff($b);
echo $interval->format("%H");
That will give you the difference in hours.
If you get valid date strings, you can use this:
$workingHours = (strtotime($end) - strtotime($start)) / 3600;
This will give you the hours a person has been working.
Another solution would be to go through the Unix-timestamp integer value difference (in seconds).
<?php
$start = strtotime('10-09-2019 12:01:00');
$end = strtotime('12-09-2019 13:16:00');
$hours = intval(($end - $start)/3600);
echo $hours.' hours'; //in hours
//If you want it in minutes, you can divide the difference by 60 instead
$mins = (int)(($end - $start) / 60);
echo $mins.' minutues'.'<br>';
?>
This solution would be a better one if your original dates are stored in Unix-timestamp format.

Categories