I need to get the next and previous months name by passing a month name to a function.
When I do this:
$date = Carbon::now(); // suppose Current month is May
$lastMonth = $date->subMonth()->format('F'); // returns April
$nextMonth = $date->addMonth()->format('F'); // returns June
The above code works fine. But I have a function where I need to pass the month name:
$month = "Feburary"; // it can be any random month
function getNextMonth($month)
{
//$date = Carbon::now();
return $date->addMonth()->format('F'); // need the output to be March
}
In this function how can I use the $month
name to get the next month name?
You could use createFromFormat
:
Carbon::createFromFormat('F-d', "$month-1")->addMonth()->format('F');
The -d
/-1
is just to make sure it will always be the beginning of the month and not overflow to the next month depending on the current date.
https://carbon.nesbot.com/docs/#api-instantiation (it's about the 10th block down from this link)