例如綜上所述多的時間,我已經多次這樣的:我怎樣才能在laravel 5.2
$a = "9:00:00";
$b = "8:00:00";
$c = "9:00:00";
等等...
必須在26:00:00,但還怎麼從45:00:00減去它?
我必須找出總出勤時間和加班時間。
例如綜上所述多的時間,我已經多次這樣的:我怎樣才能在laravel 5.2
$a = "9:00:00";
$b = "8:00:00";
$c = "9:00:00";
等等...
必須在26:00:00,但還怎麼從45:00:00減去它?
我必須找出總出勤時間和加班時間。
你可以做到以下幾點:
$sumSeconds = 0;
foreach($times as $time) {
$explodedTime = explode(':', $time);
$seconds = $explodedTime[0]*3600+$explodedTime[1]*60+$explodedTime[2];
$sumSeconds += $explodedTime;
}
$hours = floor($sumSeconds/3600);
$minutes = floor(($sumSeconds % 3600)/60);
$seconds = (($sumSeconds%3600)%60);
$sumTime = $hours.':'.$minutes.':'.$seconds;
這是suming的三倍(假定他們是在陣列)的代碼,減去將幾乎相同的代碼,但對於減法你會兩次減去$sumSeconds
,然後轉換結果。
您可以使用Carbon
找出不同之處。需要一些小技巧來添加這些時間。你可以這樣來做:
$a = '09:00:00';
$b = '08:00:00';
$c = '09:00:00';
//convert the $a in carbon instance.
//convert $b and $c in integer, you can add only integer with carbon.
$d = Carbon::createFromFormat('H:i:s',$a)->addHours(intval($b))->addHours((intval($c)));
//convert the time "45:00:00" to carbon
$e = Carbon::createFromFormat('H:i:s','45:00:00');
//return the difference
$e->diffInHours($d)
$times = [
"9:00:00",
"8:00:00",
"9:00:00",
];
// Converting the time to seconds makes calculations
// more simple and easier to understand.
function timeToSeconds($time) {
list($hours, $minutes, $seconds) = explode(":", $time);
return ($hours * 60 * 60) + ($minutes * 60) + $seconds;
}
// Let's use this to convert say 300s into 00:05:00
function formatSecondsAsHMI($seconds) {
return sprintf(
'%02d:%02d:%02d',
floor($seconds/3600),
floor($seconds/60 % 60),
floor($seconds % 60)
);
}
// Add an array of times together and return the formatted string hh:mm:ss
function addTimes($times) {
$seconds = array_sum(array_map(function ($time) {
return timeToSeconds($time);
}, $times));
return formatSecondsAsHMI($seconds);
}
// Subtract an array of times. Order of array important.
// Subtracts 0 from 1 from 2 where 0,1,2 are array keys
// i.e. [03:00:00, 10:00:00] would subtract 3 from 10 = 07:00:00
function subtractTimes($times) {
$times = array_map(function($time) {
return timeToSeconds($time);
}, $times);
return array_reduce($times, function($carry, $item) {
return ($item - $carry);
});
}
// Now just add the times together and subtract the result from 45
echo subtractTimes([addTimes($times), '45:00:00']);
難道只有永遠會是全個小時或者是有,你可以有'「八時30分零零秒」'改變? –