如何在Laravel中通过传递一个因情况而异的日期来获取上个月的最后一个日期?[副本]

vd8tlhqk  于 2023-08-08  发布在  其他
关注(0)|答案(2)|浏览(128)

此问题在此处已有答案

How do you get the first and last day using Carbon and only year and month?(4个答案)
20天前关门了。
我已经从月份字段中选择了一个月

<input class="form-control" type="month" id="report_month" name="report_month"
                                               value="{{ old('report_month') }}">

字符串
该值为“2023- 02”。
如何在控制器中获取该特定月份的最后日期?
所需数值为:2023-02-28

sauutmhj

sauutmhj1#

@php  
$lastDayofMonth1 = Carbon\Carbon::createFromFormat('Y-m', $request->input('report_month'))->endOfMonth()->day;
@endphp

字符串
另一种方式

@php  $lastDayofMonth = \Carbon\Carbon::now()->modify('-2 month')->endOfMonth()->toDateString(); @endphp


使用的->modify('-2 month')部分是动态的,我们得到值

@php  
$month = 5;
$lastDayofMonth =\Carbon\Carbon::today()->setMonth($month)->endOfMonth()->day;
@endphp

xdnvmnnf

xdnvmnnf2#

$input = $request->input('report_month'); // 2023-02
[$year, $month] = explode('-', $input);   // [2023, 02]
today()->setYear($year)->setMonth($month)->endOfMonth()->format('Y-m-d');

字符串
或者是

Carbon::createFromFormat('Y-m', $request->validated('report_month'))
    ->endOfMonth()->format('Y-m-d');

相关问题