Rav Rav - 1 year ago 104
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 Source

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'], 

Use it like:


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download