Using Carbon to return a human readable datetime difference

前端 未结 5 703
情话喂你
情话喂你 2020-12-23 09:15

I\'m using Laravel 4 to create my project.

I am currently building the comments section and I want to display how long ago the post was created, kin

相关标签:
5条回答
  • 2020-12-23 09:28

    For any version of Laravel

    $message->updated_at->diffForHumans();
    
    0 讨论(0)
  • 2020-12-23 09:36

    If you read the Carbon docs to get what you want you call the diffForHumans() method.

    <?php echo \Carbon\Carbon::createFromTimeStamp(strtotime($comment->created_at))->diffForHumans() ?>
    
    0 讨论(0)
  • 2020-12-23 09:37

    By default, Eloquent will convert the created_at, updated_at, and deleted_at columns to instances of Carbon. So, your code should be just like this:

    $comment->created_at->diffForHumans();
    

    It's very cool. It'll produce string like 2 minutes ago or 1 day ago. Plurar or singular, seconds, minutes, hours, days, weeks, or years, it runs automatically. I've tested it on Laravel version 4.1.24.

    0 讨论(0)
  • 2020-12-23 09:48
    Carbon::parse($p->created_at)->diffForHumans();
    
    0 讨论(0)
  • 2020-12-23 09:49

    use this code for time ago :

        public function time_elapsed_string($datetime, $full = false) {
        $now = new DateTime;
        $ago = new DateTime($datetime);
        $diff = $now->diff($ago);
    
        $diff->w = floor($diff->d / 7);
        $diff->d -= $diff->w * 7;
    
        $string = array(
             'y' => 'year',
             'm' => 'month',
             'w' => 'week',
             'd' => 'day',
             'h' => 'hour',
             'i' => 'minute',
             's' => 'second',
         );
         foreach ($string as $k => &$v) {
             if ($diff->$k) {
                 $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
             } else {
                 unset($string[$k]);
             }
         }
    
         if (!$full) $string = array_slice($string, 0, 1);
         return $string ? implode(', ', $string) . ' ago' : 'just now';
     }
    
    0 讨论(0)
提交回复
热议问题