Lorenz
Lorenz

Reputation: 43

How do you get the first and last day using Carbon and only year and month?

I only have 2 strings, year and month. And I need to get the first and last day using Carbon. For example, '2020' and '3' are provided. I would need to get 2 Carbon dates out of these (2020-3-1 and 2020-3-31). Is it possible?

Upvotes: 0

Views: 6407

Answers (4)

Rashed Rahat
Rashed Rahat

Reputation: 2475

To achieve your goal use the following codes:

use Carbon\Carbon; // imports the Carbon class
$year = 2020;
$month = 3;
$date_1 = Carbon::create($year, $month)->startOfMonth()->format('Y-m-d'); //returns 2020-03-01
$date_2 = Carbon::create($year, $month)->lastOfMonth()->format('Y-m-d'); //returns 2020-03-31

Happy coding :)

Upvotes: 11

Sehdev
Sehdev

Reputation: 5662

As per Carbon Documentation

Carbon::create($year, $month, $day, $hour, $minute, $second, $tz);

The only special case is for create() that has minimum value as default for missing argument but default on current value when you pass explicitly null.

So if you pass only $year and $month it will automatically considered first day and then you can format() function it to get the first day as day for e.g.

Carbon::create($year, $month)->format("Y-m-d")

Upvotes: 1

Moshiur
Moshiur

Reputation: 685

you can do it simply with carbon methods like startOfMonth and endOfMonth as below

$startOfMonth=\Carbon\Carbon::parse('2020-3')->startOfMonth()->format('Y-n-d');
$endOfMonth=\Carbon\Carbon::parse('2020-3')->endOfMonth()->format('Y-n-d');

Upvotes: 1

Japs
Japs

Reputation: 1052

I use this method to get the 1st and last day of the month.

t represents the last day of the month.

$posts = Post::whereBetween('created_at', [
Carbon::createFromDate(date('Y-m-d 00:00:00', strtotime(request('year') . '-' . request('month') . '-1'))),
Carbon::createFromDate(date('Y-m-d 23:59:59', strtotime(request('year') . '-' . request('month') . '-t')))])
->get();

return $posts

Edit: I use + on the php but it is . sorry.

or you can use this:

$this->client = $this->client->whereBetween('created_at', [
Carbon::createFromDate(date(request('year') . '-' . request('month') . '-01 00:00:00')),
Carbon::createFromDate(date(request('year') . '-' . request('month') . '-12 23:59:59'))])
->get();

Edit:(Edit:)

Base on your question you need to get the first and last day. But in the real world the 1st day is given so you need only to get the last day. It should be like this.

The first day should be given because we all know that it falls to 1.

$firstDayOfTheMonth = date(request('year') . '-' . request('month') . '-1 00:00:00');

$lastDayOfTheMonth = date(request('year') . '-' . request('month') . '-t 23:59:59');

Upvotes: -1

Related Questions