I want to get the first date and last date of the month if given I have a numeric number of the month.
For example January = 01, October = 10, November = 11
So if I pass 10 as parameter I should get the first and last date of October.
I tried to implement it using Carbon. But I gives me different result.
Here is the code. The result is is next to it.
$dt = Carbon::create(10);
echo $dt->startOfMonth(); // 0010-10-01 00:00:00
echo $dt->endOfMonth(); // 0010-10-31 00:00:00
The first day of any month is the first.
use createFromFormat
$dt = Carbon::createFromFormat('m', 10);
echo $dt->endOfMonth();
The issue is with this line:
Carbon::create(10);
Carbon's create
method takes the following list of parameters:
$year, $month, $day, $hour, $minute, $second, $tz
And you're only providing the first one. So you end up with an object representing today's date, but in the year 10.
If you want to only provide the month
argument, you should use:
Carbon::createFromFormat('m', 10);
Be aware that this will default to the current year, so results for February won't always be consistent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With