计算视图的剩余天数 Laravel,如果日期已过则为负天数

Calculate the remaining days on view Laravel, negative days if date has passed

这些是我数据库中的值,我只需要获取每个今天的剩余天数:

{{ \Carbon\Carbon::now()->diffInDays($patient->date_end) }}

要获得两个日期之间的差异,您可以通过以下方式使用碳:

$start = Carbon::parse('2022-04-30');
$end = Carbon::parse('2022-05-06');
$diff = $start->diffInDays($end);

上面,代码应该给你这个 $start$end 日期差异的天数差异。在这里,而不是静态日期 2022-04-30。您可能必须使用对象或数组值来传递它。像 $start = Carbon::parse($patient->date_start);

但是,如果你说要找出当前日期和 date_end 之间的差异,那么你可以这样做:

$end = Carbon::parse($patient->date_end);
{{ \Carbon\Carbon::now()->diffInDays($end) }}

这将为您提供结束日期和结束日期之间的差异。

而且,从你提供的细节来看,你似乎没有解析数据。您可能必须先解析它,以便它可以找到差异。

如果你想得到负值,你可能需要传递 false 作为第二个参数,diffInDays($patient->date_end, false)。除此之外,有时您仍然可能得到不正确的值,这可能是因为 timezone。假设您在 GMT -7,并且在 UTC 上它已经是一个新日期,但在您的时区中它仍然是前一天。在这种情况下,您可能会看到剩余 0 天,即使根据您的时区还剩 2 天。

在那种情况下,您可能还必须传递时区。

\Carbon\Carbon::now()->diffInDays($end,false)->timezone('America/New_York'));

the problem solved but , im confused with the may 7 , which is the 3rd row should give me a negative value

如果要获取负值,则需要将 false 作为 diffInDays 函数的第二个参数传递。

Carbon\Carbon::now()->diffInDays($patient->date_end, false)

第二个参数设置是否要绝对差值。默认为真,即returns绝对差。