Laravel 8中基于起止时间生成间隔30分钟时间数组问题求助
代码核心问题排查
- 调用
strtotime('+30 minutes', $new_time)时第二个参数传了H:i格式的字符串,而strtotime要求第二个参数必须是Unix时间戳,会直接导致时间计算失败,是返回空数组的核心原因 - 混合使用字符串比较和时间戳比较,逻辑混乱,额外添加的
$new_time . ':00' >= $to判断会提前截断符合要求的时间点 - 重复调用
strtotime和date做格式转换,冗余度高且容易出错
修复后可直接运行的代码
$available_times = []; $module = $garage->work_time; // 直接把起止时间转成时间戳计算,避免字符串比较的不确定性 $startTimestamp = strtotime($module->from); $endTimestamp = strtotime($module->to); // 30分钟对应的秒数作为步进值 $step = 1800; $currentTimestamp = $startTimestamp; while ($currentTimestamp < $endTimestamp) { // 按要求转成 h:i a 格式存入数组 $available_times[] = date('h:i a', $currentTimestamp); $currentTimestamp += $step; } return $available_times;
效果说明
如果$module->from为9:00、$module->to为12:00,输出结果和你期望的格式完全一致:
[ "09:00 am", "09:30 am", "10:00 am", "10:30 am", "11:00 am", "11:30 am" ]
如果不需要包含起始时间,要从第一个30分钟间隔后开始生成,把$currentTimestamp = $startTimestamp改成$currentTimestamp = $startTimestamp + $step即可。
内容的提问来源于stack exchange,提问作者mohamed
相关产品推荐
相关产品推荐

