4

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
Yves Gonzaga
  • 1,038
  • 1
  • 16
  • 40
  • Possible duplicate? https://stackoverflow.com/questions/2680501/how-can-i-find-the-first-and-last-date-in-a-month-using-php – sietse85 Oct 02 '17 at 10:37

2 Answers2

7

The first day of any month is the first.

use createFromFormat

$dt = Carbon::createFromFormat('m', 10);
echo $dt->endOfMonth();
Unamata Sanatarai
  • 6,475
  • 3
  • 29
  • 51
2

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.

iainn
  • 16,826
  • 9
  • 33
  • 40