我们怎样才能削减diffForHumans()
?
喜欢$post->created_at->diffForHumans()
回归时间前像3 days ago
或57 minutes ago
,或2 hours ago
。
我们怎样才能返回57 mins ago
或1W ago
等。
有什么办法吗?
搜索周围但什么都没有。
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's contribution时,这些神奇的方法只是围绕着调用diffForHumans
的冗长包装。我更喜欢这些较长的方法名称及其变体,因为它们是自我记录的。使用diffForHumans
true
的第三个参数在一年后扫描代码时并没有告诉我多少!
传递给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)
{