按条件 adding/subtracting 每月计算新日期值

Calculate new date values by conditionally adding/subtracting a month

我需要对 PHP 中的某些日期进行一些检查,以根据用户的选择从数据库中检索数据,因此我使用了以下代码:

if ($request->flagMonth == -1) {
    $query->where(
        ['month', '=', (idate('m')-1)],
        ['year', '>=', (idate('Y')-1)]
    );
}

if ($request->flagMonth == 0) {
    $query->where(
        ['month', '=', idate('m')],
        ['year', '=', idate('Y')]
    );
}

if ($request->flagMonth == 1) {
    $query->where(
        ['month', '=', (idate('m')+1)],
        ['year', '>=', idate('Y')]
    );
}

问题是:当idate('m')+1-1时,结果可能是013——当然是无效的月份值。

我可以调用其他函数来处理日期吗?

从当月的第一天创建一个日期时间对象,然后使用 $request->flagMonth 修改日期,然后调用 format()` 以访问调整后日期的所需部分。这种使用每月第一天的预防措施可防止上述 here.

出现的错误影响

不需要任何条件。

$d = new DateTime('first day of this month');
$d->modify("{$request->flagMonth} month");
$query->where(
    ['month', '=', $d->format('n')],
    ['year', '=', $d->format('Y')]
);

Demonstration

我不使用 Laravel/Carbon,但如果您必须使用包装器而不是本机函数,我希望这是一个有效的等价物,因为 addMonths() 收到一个整数:

$d = now()->firstOfMonth()->addMonths($request->flagMonth);
$query->where(
    ['month', '=', (int)$d->month],
    ['year', '=', $d->year]
);

如前所述,您正在使用 idate 获取数字月份,当然,当您减去或添加时,它不会翻转,因为它只是一个数字。最好的方法是使用 DateTime,或者因为您正在使用 Laravel、Carbon 来创建日期,进行数学计算,然后 得到数字您正在寻找。 Laravel 使用 now() 作为 Carbon::now()

的快捷方式
if ($request->flagMonth == -1) {
    $now = now()->firstOfMonth()->subMonth();
    $query->where(
        ['month', '=', $now->month],
        ['year', '>=', $now->year]
    );
}

else if ($request->flagMonth == 0) {
    $query->where(
        ['month', '=', now()->month],
        ['year', '=', now()->year]
    );
}

else if ($request->flagMonth == 1) {
    $now = now()->firstOfMonth()->addMonth();
    $query->where(
        ['month', '=', $now->month],
        ['year', '>=', $now->year]
    );
}

请注意,我在加减时使用了firstOfMonth。这是因为当您到达月底时,它会变得不稳定,因为并非所有月份都存在所有天数。