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?
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 :)
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');
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 eg
Carbon::create($year, $month)->format("Y-m-d")
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');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.