Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set next month payment date (with PHP Carbon)

I need to get a next month payment date right. So I'm taking the last due date and adding a month to it. How can I do it?

My example is: last payment was 31-st of Januarry, I'm doing

Carbon::create(2018, 1, 31, 0, 0, 0)->addMonthsNoOverflow(1)

and it works, it gives 2018-02-28 but after that next payment will be due on 28-th again. So I need to set a date after I'm adding a month.

Carbon::create(2018, 2, 28, 0, 0, 0)->addMonthsNoOverflow(1)->day(31)

it gives me 2018-03-31 which is good but if I use this formula with the first example

Carbon::create(2018, 1, 31, 0, 0, 0)->addMonthsNoOverflow(1)->day(31)

it gives me overflow 2018-03-03. And this is my problem. What should I do? Is there something like ->setDayNoOverflow(31) ?

like image 625
Yevgeniy Afanasyev Avatar asked Jul 12 '18 00:07

Yevgeniy Afanasyev


1 Answers

You should not use last payment date, but keep the first date and calculate all the other date from the first, not the previous one:

Carbon::create(2018, 1, 31, 0, 0, 0)
Carbon::create(2018, 1, 31, 0, 0, 0)->addMonthsNoOverflow(1)
Carbon::create(2018, 1, 31, 0, 0, 0)->addMonthsNoOverflow(2)
Carbon::create(2018, 1, 31, 0, 0, 0)->addMonthsNoOverflow(3)

Supposing you don't have this data, you still can:

$day = 31;
$date = Carbon::create(2018, 1, 28, 0, 0, 0);
$date->addMonthsNoOverflow(1);
$date->day(min($day, $date->daysInMonth));
like image 75
KyleK Avatar answered Sep 19 '22 07:09

KyleK