如何使用 PHP Carbon 查找下一个出现的月份第 n 天

问题描述 投票:0回答:3

我正在寻找一种方法来确定一个月中某一天的“下一次出现”。这指的是一个编号的日子(例如接下来的 30 号)。每个月都应该有一个符合条件的日期,因此,如果某个特定月份没有指定的日期,我们不会溢出到下一个月份,而是获取该月的最后一天

Carbon 提供了
    nthOfMonth 函数
  • ,但它指的是工作日。 我找到了几个答案,但他们处理的是下个月的那一天,而不是下一个合适的一天
    • 这个答案
    • 只提供了一个开始日期,而在这种情况下,我们可能是未来的几个月或几年,我们希望从那时起“赶上”订阅
    • 这个答案
    • 看起来更接近,但似乎可以使用Carbon使其更具可读性或更简洁
  • Carbon 中是否有适合此用例的内置函数?让 nthOfMonth 函数和其他函数具有“无溢出”功能而没有在其间涵盖这种情况似乎很奇怪。

php laravel php-carbon
3个回答
1
投票

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()
来代替相同的日期。
    


0
投票

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 号,它将返回当前日期。


0
投票

如果是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'); }

© www.soinside.com 2019 - 2024. All rights reserved.