简体   繁体   中英

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

@IGP answer's is correct, but;

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

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM