Laravel:碳缩短diffForHumans()

时间:2018-09-17 15:24:45

标签: php laravel laravel-5 php-carbon

我们如何缩小List<String>

diffForHumans()一样返回时间,类似于$post->created_at->diffForHumans()3 days ago57 minutes ago

我们如何能够返回2 hours ago57 mins ago等。

有什么办法吗?

  

四处搜寻,但一无所获。

3 个答案:

答案 0 :(得分:4)

碳通过魔术方法实现不同的通话时间配置。 backing trait中记录了所有可能的配置。通过这些方法进行扫描,看起来像是 class MainActivity : AppCompatActivity() { @RequiresApi(Build.VERSION_CODES.JELLY_BEAN) fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) button.setOnClickListener(){ var img : ImageView? = imageView val sendIntent = Intent() sendIntent.action = Intent.ACTION_SEND sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(img.toString())) sendIntent.type = "image/jpeg" startActivity(Intent.createChooser(sendIntent, "Share image to : ")) } }

shortRelativeDiffForHumans

否则,您可以使用str_replace或类似的字符串函数来调整结果值。

我将注意到,响应@Giovanni's contribution,这些魔术方法只是对$c = new Carbon\Carbon('now -1 day 4 hours'); dump($c->diffForHumans(), $c->shortRelativeDiffForHumans()); "20 hours ago" "20h ago" 调用的冗长包装。我喜欢这些较长的方法名称及其变体,因为它们是自记录的。一年后扫描代码时,使用diffForHumans的第三个参数diffForHumans并不能告诉我多少!

答案 1 :(得分:2)

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

答案 2 :(得分:1)

尝试一下。

shortRelativeDiffForHumans()

Docs