Laravel Carbon如何在现有代码中限制周末、节假日及非工作时段?
在Laravel Carbon中添加节假日与周末的日期限制
一、周末限制实现
Carbon内置了isWeekend()方法,可直接判断日期是否为周六或周日,无需复杂的差值计算。在现有日期范围校验逻辑后,添加以下判断即可:
if ($dateTime->isWeekend()) { return Redirect::back()->with("error-modal", "Weekends are not available for selection, please choose a weekday date and time."); }
二、特定节假日限制实现
- 先定义包含所有节假日日期的数组,日期格式统一为
Y-m-d(与$dateTime转换后的格式匹配):
$holidays = [ '2024-01-01', // New Year's Day '2024-02-10', // Spring Festival '2024-04-04', // Qingming Festival // 按需添加更多节假日 ];
- 接着判断选中的日期是否在节假日数组中,同样放在范围校验之后:
if (in_array($dateTime->format('Y-m-d'), $holidays)) { return Redirect::back()->with("error-modal", "The selected date is a holiday and cannot be chosen. Please select another date."); }
整合到现有代码的完整示例
将上述判断插入到现有代码的日期范围校验之后,完整代码如下:
$callBackDateTime = Input::get("datetime"); try { $dateTime = Carbon::createFromFormat("F d Y - h:iA", $callBackDateTime); } catch (InvalidArgumentException $err) { $dateTime = null; } if (!$dateTime) { return Redirect::back()->with("error-modal", "Invalid date or time, please try again."); } $now = new Carbon; $now->second = 0; $limit = new Carbon; $limit->addDays(60); $limit->hour = 23; $limit->minute = 59; $limit->second = 59; if ($dateTime->lt($now)) { return Redirect::back()->with("error-modal", "The date and time you entered is in the past. Please enter a date and time after now."); } if ($dateTime->gt($limit)) { return Redirect::back()->with("error-modal", "The date and time you entered is more than 60 days away. Please enter a date and time within the next 60 days."); } // 新增:周末限制判断 if ($dateTime->isWeekend()) { return Redirect::back()->with("error-modal", "Weekends are not available for selection, please choose a weekday date and time."); } // 新增:节假日限制判断 $holidays = [ '2024-01-01', '2024-02-10', '2024-04-04', // 按需添加更多节假日 ]; if (in_array($dateTime->format('Y-m-d'), $holidays)) { return Redirect::back()->with("error-modal", "The selected date is a holiday and cannot be chosen. Please select another date."); } $this->orderInProgress = Input::get("submit"); $this->orderInProgress = isset($this->orderInProgress) ? $this->orderInProgress : false;
内容的提问来源于stack exchange,提问作者Zero_Cool09
相关产品推荐
相关产品推荐

