【问题标题】:Laravel : Carbon shorten diffForHumans()Laravel:碳缩短 diffForHumans()
【发布时间】:2018-09-17 15:24:44
【问题描述】:

我们如何修剪diffForHumans()

点赞$post->created_at->diffForHumans() 回复之前的时间点赞3 days ago57 minutes ago2 hours ago

我们如何才能返回57 mins ago1W ago 等。

有什么办法吗?

四处寻找,但一无所获。

【问题讨论】:

    标签: php laravel laravel-5 php-carbon


    【解决方案1】:

    传递给 diffForHumans() 的第三个值用于缩短显示输出。

    试试类似的,

    $post->created_at->diffForHumans(null, false, true)
    

    在这里您可以看到 diffForHumans() 的 cmets 及其接受的值。


         /**
         * 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】:

      试试这个。

      shortRelativeDiffForHumans()
      

      Docs

      【讨论】:

        【解决方案3】:

        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 的调用的详细包装。我更喜欢这些较长的方法名称及其变体,因为它们是自记录的。一年后扫描代码时,使用true 的第三个参数diffForHumans 并不能告诉我太多!

        【讨论】:

          猜你喜欢
          • 2023-03-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-06-13
          • 2017-08-27
          • 1970-01-01
          • 2020-02-19
          • 1970-01-01
          相关资源
          最近更新 更多