PHP实现按指定次数拆分一天时间的函数需求
Solution for PHP
split_times() Function I've put together a robust PHP function that exactly meets your requirement of splitting a 24-hour day into specified intervals and returning the formatted time array. Here's how it works:
Approach
- Input Validation: First, we check that the input is a positive integer to avoid invalid splits.
- Calculate Interval: Convert the 24-hour day into total seconds (86400), then divide by the number of intervals to get the step size in seconds.
- Generate Times: Loop through each interval, calculate the corresponding time in seconds from the start of the day, then format it into
HH:MM:SSusinggmdate()(to avoid timezone discrepancies).
The Function Code
function split_times($interval) { // Ensure we're working with a valid positive integer if (!is_int($interval) || $interval <= 0) { return []; } $timeArray = []; $totalDailySeconds = 24 * 3600; // Total seconds in a day $stepSeconds = $totalDailySeconds / $interval; for ($i = 0; $i < $interval; $i++) { // Calculate seconds from midnight for the current interval $currentSeconds = $i * $stepSeconds; // Format to HH:MM:SS (gmdate avoids timezone shifts) $timeArray[] = gmdate('H:i:s', $currentSeconds); } return $timeArray; }
Test Examples
Let's verify with your provided cases:
split_times(2)returns:['00:00:00', '12:00:00']split_times(4)returns:['00:00:00', '06:00:00', '12:00:00', '18:00:00']split_times(6)returns:['00:00:00', '04:00:00', '08:00:00', '12:00:00', '16:00:00', '20:00:00']
This function also handles non-divisible intervals gracefully. For example, split_times(5) would return:['00:00:00', '04:48:00', '09:36:00', '14:24:00', '19:12:00']
Key Notes
- Using
gmdate()ensures that we don't get timezone offsets (e.g., if your server is in a UTC+X timezone,date()would shift the midnight time). - The input validation ensures the function doesn't break with invalid inputs like 0, negative numbers, or non-integers.
内容的提问来源于stack exchange,提问作者user1877978
相关产品推荐
相关产品推荐

