我正在寻找一种方法来确定一个月中某一天的“下一次出现”。这指的是一个编号的日子(例如接下来的 30 号)。每个月都应该有一个符合条件的日期,因此,如果某个特定月份没有指定的日期,我们不会溢出到下一个月份,而是获取该月的最后一天。
Carbon 提供了
public function nextNthNoOverflow(int $nth, Carbon $from): Carbon
{
// Get the fitting day on the $from month as a starting point
// We do so without overflowing to take into account shorter months
$day_in_month = $from->copy()->setUnitNoOverflow('day', $nth, 'month');
// If the date found is greater than the $from starting date we already found the next day
// Otherwise, jump to the next month without overflowing
return $day_in_month->gt($from) ? $day_in_month : $day_in_month->addMonthNoOverflow();
}
由于我们在上次比较中使用了
$from
日期,因此我们要确保之前使用
copy()
,这样就不会弄乱日期。另外,根据您的需要,您可以考虑使用 gte()
来代替相同的日期。use Carbon\Carbon;
$date = Carbon::now(); $day = 30; // the 30th of the month
$nextOccurrence = $date->next(function (Carbon $date) use ($day) {
return $date->day == $day; });
echo $nextOccurrence;
这将输出该月第 30 天的下一次出现,并考虑当前日期。如果当前日期已经是该月的 30 号,它将返回当前日期。
如果是28号。 2 月,我想接收下一个 31 日,该函数返回 28 日或 3 月,而不是 3 月 31 日。
在添加月份后必须再次添加 setUnitNoOverflow,才能恢复到正确的日期。
public function nextNthNoOverflow(int $nth, Carbon $from): Carbon
{
// Get the fitting day on the $from month as a starting point
// We do so without overflowing to take into account shorter months
$day_in_month = $from->copy()->setUnitNoOverflow('day', $nth, 'month');
// If the date found is greater than the $from starting date we already found the next day
// Otherwise, jump to the next month without overflowing and set the nth again
return $day_in_month->gt($from)
? $day_in_month
: $day_in_month->addMonthNoOverflow()->setUnitNoOverflow('day', $nth, 'month');
}