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
Related
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
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);
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/
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?
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.