I would like to compare 2 dates. So I create a condition like this in my template blade:
@if(\Carbon\Carbon::parse($contrat->date_facturation)->format('d/m/Y') < $dateNow)
<td class="danger">
{{ \Carbon\Carbon::parse($contrat->date_facturation)->format('d/m/Y') }}
</td>
@else
<td>
{{ \Carbon\Carbon::parse($contrat->date_facturation)->format('d/m/Y') }}
</td>
@endif
Run Code Online (Sandbox Code Playgroud)
My variable $dateNow has the same format on my value in $contract->date_facturation
It add a red background on the date 25/02/2018 while the date is not less than the variable $contract->date_facturation
Do you have any idea of ??the problem?
Thank you
The problem is that you are trying to compare two date strings. PHP don't know how to compare date strings.
Carbon::format() returns a string. You shoud convert your dates to a Carbon object (using parse) and use Carbon's comparison methods, as described on Carbon Docs (Comparison).
For your example, you should do:
// Note that for this work, $dateNow MUST be a carbon instance.
@if(\Carbon\Carbon::parse($contrat->date_facturation)->lt($dateNow))
<td class="danger">
{{ \Carbon\Carbon::parse($contrat->date_facturation)->format('d/m/Y') }}
</td>
@else
<td>
{{ \Carbon\Carbon::parse($contrat->date_facturation)->format('d/m/Y') }}
</td>
@endif
Run Code Online (Sandbox Code Playgroud)
同样,您的代码看起来是重复的,并且假设这$dateNow是具有当前日期的变量,则可以使用Carbon::isPast()method,因此重写代码将变成:
<?php
$date_facturation = \Carbon\Carbon::parse($contrat->date_facturation);
?>
@if ($date_facturation->isPast())
<td class="danger">
@else
<td>
@endif
{{ $date_facturation->format('d/m/Y') }}
</td>
Run Code Online (Sandbox Code Playgroud)
由于您将日期解析一次而不是两次,因此这使您的代码重复性和速度降低。
另外,如果您希望代码更好,请使用Eloquent的Date Mutators,因此您无需每次在视图上都需要解析日期。
| 归档时间: |
|
| 查看次数: |
5261 次 |
| 最近记录: |