Rav Rav - 11 days ago 6
PHP Question

Laravel - return time ago like "2d ago"

What is the best way to convert PHP date to format like this:

3d ago
18h ago


Having to implement this functionality for each project can be tiresome.

Rav Rav
Answer

The best thing I was able to come with was this model method:

public function getTimeAgo($carbonObject) {
    return str_ireplace(
        [' seconds', ' second', ' minutes', ' minute', ' hours', ' hour', ' days', ' day', ' weeks', ' week'], 
        ['s', 's', 'm', 'm', 'h', 'h', 'd', 'd', 'w', 'w'], 
        $carbonObject->diffForHumans()
    );
}

Use it like:

$message->getTimeAgo($message->created_at);

Example output:

  • 2d ago
  • 3w ago

Notice: Carbon->diffForHumans() actually returns 3 days ago and 18 hours ago so I needed to use str_ireplace function