Home > OS >  Receiving the last day of the next month with PHP Carbon
Receiving the last day of the next month with PHP Carbon

Time:03-08

If the date is the last day of the month, I want to get the last day of the next month. I don't want the time to change.

Original date -> 2022-31-01 14:00:00
I need        -> 2022-28-02 14:00:00

Original date -> 2022-28-02 14:00:00
I need        -> 2022-31-03 14:00:00

CodePudding user response:

  • $date->lastOfMonth() returns the last day of $date's month.
  • $date->isLastOfMonth() returns true if $date is the last day of the month.

Assuming $date is a Carbon instance, then it's just a matter of using a few functions and a ternary operator.

$result = $date->isLastOfMonth()
    ? $date->addDays(1)->lastOfMonth()
    : $date;

To keep the time part of the date, you'll need to create an interval first and add it later.

$interval = $date->diffAsCarbonInterval($date->startOfDay());

$result = $date->isLastOfMonth()
    ? $date->addDays(1)->lastOfMonth()->add($interval)
    : $date;

CodePudding user response:

@IGP answer's is correct, but;

$date->startOfDay() -> changes your original date.

you should use $date->copy()->startOfDay()

  • Related