'PHP Parse time Days/hours/minutes + round up to closest step
I Have system, where people ar tracking there spent time on project. After project is ending, I want to count there spent time + round up to closest step
For now, I have function, that only convert time to readable format
function parse_time($t, $k="",$step){
if($t == 0){
if($k == ""){
return $t;
}
return $k;
} else {
if($t >= 3600){
$h=floor($t/3600);
$a=$t%3600;
if($a >= 60){
$m=round($a/60);
} else {
$m=0;
}
} else{
$h=0;
$m=round($t/60);
}
$d=($d > 0)?$d."d":"";
$h=($h > 0)?$h."h":"";
$m=($m > 0)?$m."min":"";
$t=$d.$h.$m;
return $t;
}
}
I want to add parameter to function step ( in minutes ), So
If the step = 5 parsed time 41h 20min output 41h 25min
If the step = 15 parsed time 41h 20min output 41h 30min
If the step = 20 parsed time 41h 20min output 41h 20min
If the step = 30 parsed time 41h 20min output 41h 30min
If the step = 60 parsed time 41h 20min output 42h 0min
If the step = 180 parsed time 41h 20min output 42h 0min
If the step = 0 parsed time 41h 20min output 41h 20min
What would be best solution to do that? Thank you :)
Solution 1:[1]
The solution is to convert all times and intervals to seconds and then work with modulo (%).
First of all, I'll give you two useful help functions.
function strTimeToSeconds(string $time): int {
return strtotime('1970-01-01 '.$time.' UTC');
}
function secondsToHuman(int $seconds):string {
$hours = (int)($seconds/3600);
$seconds -= $hours * 3600;
return $hours.':'.gmdate('i:s',$seconds);
}
A example. Given are 148800 seconds (=41hours 20min).
$seconds = 148800;
$interval = strTimeToSeconds('15 minutes'); //900 Sec
Round up to closest interval:
$seconds = $seconds - $seconds%$interval + $interval; //149400
To convert seconds to hours, minutes and seconds we now use secondsToHuman().
echo secondsToHuman($seconds); //41:30:00
Solution 2:[2]
Thanks @jspit
Works as expected :)
function step($a, $b) {
if ($a == 0){$seconds = 0;} else {$seconds = $a-1;}
if ($b == 0){$step = 0;} else {$step = $b*60;}
$seconds = $seconds - $seconds%$step + $step;
return $seconds;
}
echo secondsToHuman(step(3900, 5));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | jspit |
Solution 2 | Elvis Loksts |