Search code examples
phplaravelphp-carbon

Set day with no overflow (with PHP Carbon)


I use Carbon (PHP library) to set day to a date. But I want it not going to the next month, but rather stop and the end of month. Example:

Carbon::create(2018, 2, 27, 0, 0, 0)->day(31);

I'm getting

2018-03-03 00:00:00

But I need

2018-02-28 00:00:00

When you operate months Carbon gives you ->subMonthsNoOverflow() and ->addMonthsNoOverflow() which is really helpful but there is nothing like this for setting a day.


Solution

  • The answer is

    $day = 31;
    $date = Carbon::create(2018, 2, 27, 0, 0, 0);
    $date->day(min($day, $date->daysInMonth));