簡體   English   中英

使用diffForHumans()方法將now()與datetime的碳差異與“之前”相比較

[英]Carbon difference of now() vs datetime with “ago” using diffForHumans() method

根據手冊: http//carbon.nesbot.com/docs/#api-humandiff

得到一個ago

將過去的值與默認值進行比較時

但不管我做什么,我不能得到的ago

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

結果到before ,而

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

結果到after

但正如你可以清楚地看到我上面的兩個片段比較past ($ datetime)和現在的默認值(Carbon :: now())所以我無法理解為什么我不能在以前獲得? 希望有人可以提供幫助。 我只需要呼應ago 謝謝!

您應該使用不帶參數的diffForHumans()並在'date calculation'之后使用,例如:

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 $users->created_at是一個像2018-05-03 14:54:14這樣的日期,這將給出一個像2周前一樣的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM