当我尝试通过 PHP 或 Laravel Carbon 获取下个月的最后一天时,一切正常,但是当我尝试从特定日期(2023-01-31)获取下个月的最后一天时,
date('Y-m-01', strtotime('next month', strtotime('2023-01-31')));
或
Carbon::createFromFormat('Y-m-d H:m:00:000', '2023-01-31')->addMonth()->format('Y-m-t H:m:00:000');
该时间输出结果于2023-03-31给出,但下个月的最后一天是2023-02-28。那么我该如何解决呢?它无法正常工作。
$instituter = Institute::where('code', $instInfo->institute_code)->first();
// $institute = Carbon::createFromFormat('Y-m-d H:m:00:000', $institute->institute_expire)->addMonth()->format('Y-m-d H:m:00:000');
// $expire = $instituter->institute_expire;
// $inst = Carbon::createFromFormat('Y-m-d H:i:00.000', $instituter->institute_expire)->addMonths(6)->startOfMonth()->format('Y-m-d');
$inst = date('Y-m-01', strtotime('next month', strtotime($instituter->institute_expire)));
// $inst = Carbon::createFromFormat('Y-m-d H:i:00.000', $instituter->institute_expire)->addMonths(6)->startOfMonth();
// $institute = Carbon::createFromFormat('m/d/Y', $instituter->institute_expire)->addMonth();
从 Laravel 5.5 开始,你可以使用 now() 函数来获取当前日期和时间,并且你可以使用以下方法获取下个月的最后一个日期:
now()->addMonth()->endOfMonth();
如果你想格式化为Y-m-d
now()->addMonth()->endOfMonth()->format('Y-m-d');
或者如果您只想将日期更改格式为 $now->format('d');
如果您使用的 Laravel 版本低于 5.5,请使用上述函数
\Carbon\Carbon::now()->addMonth()->endOfMonth();
日期以字符串形式给出。
$strDate = '2023-01-15';
基于此日期,将创建下个月最后一天的日期对象。使用 DateTime 这可以在一行中完成。
$lastDdayOfNextMonth = date_create('last day of next month '.$strDate);
Carbon 是 DateTime 的扩展。因此这也有效:
$lastDdayOfNextMonth = Carbon::create('last day of next month '.$strDate);
echo $lastDdayOfNextMonth->format('c');
//2023-02-28T00:00:00+01:00
如果日期已经作为对象存在,则变得更加容易。
$dt = new DateTime('2023-01-15');
$lastDdayOfNextMonth = $dt->modify('last day of next month');
这与碳的工作原理完全相同。
$dt = new Carbon('2023-01-15');
$lastDdayOfNextMonth = $dt->modify('last day of next month');
谨防使用带有 Carbon 的 addMonth() 或仅使用 DateTime 的“下个月”的解决方案。与问题一样,旧版本也会返回日期“2023-01-31”的不正确结果。 Carbon 有一种特殊的方法来添加“不溢出”的月份:addMonthsNoOverflow()
$endOfNextMonth = Carbon::create('2023-01-31')
->addMonthsNoOverflow(1)
->endOfMonth()
;
echo $endOfNextMonth; //2023-02-28 23:59:59
strtotime 会做到这一点...
例如
echo date('c', strtotime('last day of next month'));
给出例如2023-02-28T19:53:34+00:00,今天是 2023/01/21。
或者-
ècho (new DateTime('last day of next month'))->format('c')
也可以工作
这是了解实际需求后更新的答案。
// Get the today date
$todayDate = Carbon::now();
// Calculate the first day of the next month
$firstDayOfNextMonth = $todayDate->copy()->addMonth()->startOfMonth();
// Calculate the last day of the next month
$lastDayOfNextMonth = $firstDayOfNextMonth->copy()->endOfMonth();
// Formatted date
$formattedLastDay = $lastDayOfNextMonth->format('Y-m-d');