To find the first and last day of a month using Carbon in PHP, you can use the following code:
use Carbon\Carbon;
$month = 6; // desired month number
$year = 2022; // desired year
$firstDay = Carbon::createFromDate($year, $month, 1)->startOfMonth()->toDateString();
$lastDay = Carbon::createFromDate($year, $month, 1)->endOfMonth()->toDateString();
echo "First day of the month: " . $firstDay . "\n";
echo "Last day of the month: " . $lastDay;
In this example, we are finding the first and last day of June 2022.
The Carbon::createFromDate()
function is used to create a new Carbon instance from the given year, month, and day. We pass the year and month provided by the user and set the day to 1, as we want to find the first day of the month.
We then use the startOfMonth()
and endOfMonth()
functions to get the first and last day of the month, respectively. Finally, we convert the resulting dates to a formatted string using toDateString()
.
Running this code will output:
First day of the month: 2022-06-01
Last day of the month: 2022-06-30
You can customize the value of $month
and $year
to get the first and last day of any desired month.