[英]Laravel : Carbon shorten diffForHumans()
我們如何修剪diffForHumans()
?
Like $post->created_at->diffForHumans()
返回時間之前 Like 3 days ago
或57 minutes ago
或2 hours ago
。
我們怎么能在57 mins ago
或1W ago
等返回。
有什么辦法嗎?
四處尋找,但一無所獲。
傳遞給 diffForHumans() 的第三個值用於縮短顯示輸出。
嘗試類似的東西,
$post->created_at->diffForHumans(null, false, true)
在這里,您可以看到 diffForHumans() 的注釋及其接受的值。
/**
* Get the difference in a human readable format in the current locale.
*
* When comparing a value in the past to default now:
* 1 hour ago
* 5 months ago
*
* When comparing a value in the future to default now:
* 1 hour from now
* 5 months from now
*
* When comparing a value in the past to another value:
* 1 hour before
* 5 months before
*
* When comparing a value in the future to another value:
* 1 hour after
* 5 months after
*
* @param Carbon|null $other
* @param bool $absolute removes time difference modifiers ago, after, etc
* @param bool $short displays short format of time units
* @param int $parts displays number of parts in the interval
*
* @return string
*/
public function diffForHumans($other = null, $absolute = false, $short = false, $parts = 1)
{
Carbon 通過魔術方法實現不同的調用時間配置。 可能配置的范圍都記錄在backing trait 中。 瀏覽這些方法,看起來你想要shortRelativeDiffForHumans
:
$c = new Carbon\Carbon('now -1 day 4 hours');
dump($c->diffForHumans(), $c->shortRelativeDiffForHumans());
"20 hours ago"
"20h ago"
如果做不到這一點,您可以使用str_replace
或類似的字符串函數來調整結果值。
我會注意到,作為對@Giovanni貢獻的回應,這些魔術方法只是對diffForHumans
調用的詳細包裝。 我更喜歡這些較長的方法名稱及其變體,因為它們是自記錄的。 一年后掃描代碼時,使用diffForHumans
的第三個參數true
並不能告訴我太多!
{{ $product->created_at->diffForHumans(null, false, 1) }}
結果:14h 前、14m 前等......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.