How to get difference of time in human readable wi

2019-02-08 07:16发布

I want to display the difference between the current date and time with the one stored in the updated_at column. However, I want it to be human-friendly like:

53 mins ago
2 hours ago
3 days ago

Is there any function out there that I could use to make it easier?

To be sure that you understand me, let's say I have in my database a column (updated_at) which is equal to 2015-06-22 20:00:03 and the the current time is 20:00:28 then I'd like to see:

25 mins ago 

When it's higher than 59 minutes, I want to show only hours and when it's higher than 24 hours I'd like to see how many days ago.

1条回答
何必那么认真
2楼-- · 2019-02-08 08:03

By default, Eloquent converts created_at and updated_at columns to instances of Carbon. So if you are fetching the data using Eloquent, then you can do it as below.

$object->updated_at->diffForHumans();

If you want to customize the fields that will be mutated automatically, then within your model, you can customize them as you wish.

// Carbon instance fields
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
查看更多
登录 后发表回答