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

laravel - Carbon | diffForHumans() shorter version?

我正在尝试找出如何缩短 laravel 中 Carbon 库提供的 diffForHumans 方法的输出。

diffForHumans 的默认格式是这样的:来自文档

但我希望输出类似于:

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

我怎样才能做到这一点?

根据 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) {
    ...
}

要删除修饰符,请将第二个参数作为 true 传递,如果要缩短时间,请将第三个参数作为 true

源代码位于

vendor/nesbot/carbon/src/Carbon/Carbon.php

Carbon 给你一个选项来删除 'ago'

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

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

对于Just now,您需要指定just now的长度。