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

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.");
}

二、特定节假日限制实现

  1. 先定义包含所有节假日日期的数组,日期格式统一为Y-m-d(与$dateTime转换后的格式匹配):
$holidays = [
    '2024-01-01', // New Year's Day
    '2024-02-10', // Spring Festival
    '2024-04-04', // Qingming Festival
    // 按需添加更多节假日
];
  1. 接着判断选中的日期是否在节假日数组中,同样放在范围校验之后:
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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 04:05:43