Laravel:碳缩短diffForHumans()

问题描述 投票:2回答:3

我们怎样才能削减diffForHumans()

喜欢$post->created_at->diffForHumans()回归时间前像3 days ago57 minutes ago,或2 hours ago

我们怎样才能返回57 mins ago1W ago等。

有什么办法吗?

搜索周围但什么都没有。

php laravel laravel-5 php-carbon
3个回答
4
投票

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的第三个参数在一年后扫描代码时并没有告诉我多少!


3
投票

传递给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)
    {

1
投票

试试这个。

shortRelativeDiffForHumans()

Docs

© www.soinside.com 2019 - 2024. All rights reserved.