You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 10:24:05