如何在Laravel中通过传递根据情况变化的日期来获取月份的最后一天?

huangapple go评论58阅读模式
英文:

How to get last date of month by passing a date which varies on situation in Laravel?

问题

我已从月份字段中选择了一个月。

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

该值为'2023-02'。

如何在控制器中获取该特定月份的最后日期?

所需值为:2023-02-28

英文:

I have selected a month from month field

&lt;input class=&quot;form-control&quot; type=&quot;month&quot; id=&quot;report_month&quot; name=&quot;report_month&quot;
                                               value=&quot;{{ old(&#39;report_month&#39;) }}&quot;&gt;

That value is '2023-02'.

How to get last date of that specific month in controller?

Value required is :2023-02-28

答案1

得分: 1

Sure, here are the translated parts:

@php
$lastDayofMonth1 = Carbon\Carbon::createFromFormat('Y-m', $request->input('report_month'))->endOfMonth()->day;
@endphp
@php $lastDayofMonth = \Carbon\Carbon::now()->modify('-2 months')->endOfMonth()->toDateString(); @endphp
@php
$month = 5;
$lastDayofMonth = \Carbon\Carbon::today()->setMonth($month)->endOfMonth()->day;
@endphp
英文:
@php  
$lastDayofMonth1 = Carbon\Carbon::createFromFormat(&#39;Y-m&#39;, $request-&gt;input(&#39;report_month&#39;))-&gt;endOfMonth()-&gt;day;
@endphp 

another ways

@php  $lastDayofMonth = \Carbon\Carbon::now()-&gt;modify(&#39;-2 month&#39;)-&gt;endOfMonth()-&gt;toDateString(); @endphp

used -&gt;modify(&#39;-2 month&#39;) part is dynamically, we get values

OR

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

答案2

得分: 0

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

or

Carbon::createFromFormat('Y-m', $request->validated('report_month'))
    ->endOfMonth()->format('Y-m-d');
英文:
$input = $request-&gt;input(&#39;report_month&#39;); // 2023-02
[$year, $month] = explode(&#39;-&#39;, $input);   // [2023, 02]
today()-&gt;setYear($year)-&gt;setMonth($month)-&gt;endOfMonth()-&gt;format(&#39;Y-m-d&#39;);

or

Carbon::createFromFormat(&#39;Y-m&#39;, $request-&gt;validated(&#39;report_month&#39;))
    -&gt;endOfMonth()-&gt;format(&#39;Y-m-d&#39;);

huangapple
  • 本文由 发表于 2023年7月18日 15:29:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76710421.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定