Laravel刀片比较两个日期 [英] Laravel blade compare two date

查看:269
本文介绍了Laravel刀片比较两个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较2个日期.因此,我在模板刀片中创建了这样的条件:

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

我的变量$ dateNow在$ contract-> date_facturation中的值具有相同的格式

My variable $dateNow has the same format on my value in $contract->date_facturation

截图

它在日期25/02/2018上添加红色背景,而该日期不少于变量$ 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?

谢谢

推荐答案

问题是您正在尝试比较两个日期字符串. PHP不知道如何比较日期字符串.

The problem is that you are trying to compare two date strings. PHP don't know how to compare date strings.

Carbon::format()返回一个字符串.您应按照碳文件"(比较).

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

另外,您的代码看起来很重复,并且假设$dateNow是具有当前日期的变量,则可以使用Carbon::isPast()方法,因此重写代码将变成:

Also your code looks repetitive, and assuming that $dateNow is a variable with current date, you can use Carbon::isPast() method, so rewriting your code, it becomes:

@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>

这使您的代码重复性和速度更快,因为您只将日期解析两次,而不是两次.

This makes your code less repetitive and faster, since you parse the date once, instead of twice.

如果您想更好地编写代码,请使用 Eloquent的日期变量,因此您无需每次查看视图时都解析日期.

Also if you want your code better, use Eloquent's Date Mutators, so you won't need to parse dates everytime that you need on your views.

这篇关于Laravel刀片比较两个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆