According to the manual: http://carbon.nesbot.com/docs/#api-humandiff
to get an ago
When comparing a value in the past to default now
but whatever I do, I cannot get the ago
return $datetime->diffForHumans(Carbon::now())
results to before
, while
return Carbon::now()->diffForHumans($datetime);
results to after
,
but as you can see clearly both of my snippet above compares the past
($datetime) and to default now (Carbon::now()) so I cannot understand why I can't get an ago? Hope somebody can help. I just need to echo ago
. Thanks!
答案 0 :(得分:4)
您应该在没有参数的情况下使用diffForHumans()
,并在“'日期计算”后使用,例如:
Carbon::now()->subDays(24)->diffForHumans(); // "3 weeks ago"
或者,如果您有日期,则可以使用$datetime->diffForHumans();
:
$datetime = Carbon::createFromDate(2015, 8, 25); // or your $datetime of course
return $datetime->diffForHumans(); // "1 week ago"
答案 1 :(得分:2)
虽然@baao给出了一个很好的答案,但是如果你传递一个原始日期输入,那么Carbon::createFromDate()
函数可能会有问题,如Laravels created_at
。现在你必须使用不同的功能。看看下面。
$carbondate = Carbon::parse($users->created_at);
$past = $carbondate->diffForHumans();
dd($past);
其中$users->created_at
是2018-05-03 14:54:14
之类的日期,然后会给出2周前的答案。