laravel - 碳 | diffForHumans() 更短的版本?

Sap*_*aik 4 php date laravel php-carbon laravel-5.4

我试图弄清楚如何缩短diffForHumanslaravel 中 Carbon 库提供的方法的输出。

默认格式diffForHumans是这样的:从文件

  • 将过去的值与现在的默认值进行比较时:

    1. 5 个月前

    2. 1小时前

但我希望输出类似于:

  1. 1 小时
  2. 5 分钟
  3. 5个月
  4. 2年
  5. 现在

我怎样才能做到这一点?

lin*_*ref 9

根据源代码 diffForHumans

/**
 * Get the difference in a human readable format in the current locale.
 *
 *
 * @param Carbon|null $other
 * @param bool        $absolute removes time difference modifiers ago, after, etc
 * @param bool        $short    displays short format of time units
 *
 * @return string
 */
public function diffForHumans(Carbon $other = null, $absolute = false, $short = false) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

删除修饰符,传递第二个参数 astrue并获得缩短的时间版本传递第三个参数 astrue

源代码在

vendor/nesbot/carbon/src/Carbon/Carbon.php
Run Code Online (Sandbox Code Playgroud)


Ray*_*eng 6

Carbon 为您提供删除“前”的选项

$time = \Carbon\Carbon::now()->subMinutes(1)->diffForHumans(null, true)

在此处输入图片说明

如果您需要使用“1 小时,5 分钟”,只需str_replace(['hours', 'minutes'], ['h', 'mins'], $time)

对于Just now,您需要指定多长时间just now