zelensky
zelensky

Reputation: 11

Receiving the last day of the next month with PHP Carbon

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

Upvotes: 1

Views: 1272

Answers (3)

jspit
jspit

Reputation: 7703

Carbon is an extension of DateTime. However, Carbon is not needed here as there is a very simple solution using DateTime. It only has to be checked whether the day of the date (d) matches the last day of the month (t). if so, then it is modified to the last day of the next month. Time remains unaffected.

$dt = new DateTime('2022-01-31 14:00:00');

if($dt->format('d') == $dt->format('t')){
  $dt->modify('last Day of next month');
}

//test output
echo $dt->format('Y-m-d H:i:s')."\n";

Try self.

Upvotes: 0

Zelensky
Zelensky

Reputation: 57

@IGP answer's is correct, but;

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

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

Upvotes: 1

IGP
IGP

Reputation: 15786

  • $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;

Upvotes: 2

Related Questions