Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first and last date of the month from a given numeric month PHP

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
like image 451
Yves Gonzaga Avatar asked Jan 29 '23 11:01

Yves Gonzaga


2 Answers

The first day of any month is the first.

use createFromFormat

$dt = Carbon::createFromFormat('m', 10);
echo $dt->endOfMonth();
like image 183
Unamata Sanatarai Avatar answered Feb 01 '23 01:02

Unamata Sanatarai


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.

like image 42
iainn Avatar answered Feb 01 '23 00:02

iainn