使用 diffForHumans() 方法 "ago" 的 now() 与 datetime 的碳差异

Carbon difference of now() vs datetime with "ago" using diffForHumans() method

根据手册:http://carbon.nesbot.com/docs/#api-humandiff

获得ago

When comparing a value in the past to default now

但是无论我做什么,我都无法得到 ago

return $datetime->diffForHumans(Carbon::now())

结果为 before,而

return Carbon::now()->diffForHumans($datetime);

结果为 after

但是你可以清楚地看到我上面的两个代码片段比较了 past($datetime) 和现在默认 (Carbon::now()) 所以我不明白为什么我不能得到前?希望有人能帮忙。我只需要回应 ago。谢谢!

您应该在 'date calculation' 之后使用不带参数的 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"

虽然@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 周前这样的答案。