php 如何使用 Laravel 5 获得人类可读格式的时间差异?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30991992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:11:08  来源:igfitidea点击:

How do I get the difference of time in human readable format with Laravel 5?

phptimelaravel-5

提问by Matthieu Boisjoli

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

我想显示当前日期和时间与updated_at列中存储的日期和时间之间的差异。但是,我希望它对人友好,例如:

53 mins ago
2 hours ago
3 days ago

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

有没有可以让我更轻松地使用的功能?

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

为确保您理解我的意思,假设updated_at我的数据库中有一个列 ( ),它等于2015-06-22 20:00:03并且当前时间是20:00:28。那我想看看:

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.

当它高于 59 分钟时,我只想显示小时,当它高于 24 小时时,我想查看多少天前。

回答by Burak

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

默认情况下,雄辩转换created_atupdated_at列的情况下,。因此,如果您使用 Eloquent 获取数据,那么您可以按如下方式进行。

$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'];

回答by Wainaina Nik

incase of the date is in a string format, use laravel Carbon; e.g,

如果日期是字符串格式,请使用 laravel Carbon;例如,

 {{ \Carbon\Carbon::parse($on_revision->assignment->deadline)->diffForhumans() }}

Notice how I wrap my string in the carbon::parse()

请注意我如何将字符串包装在 carbon::parse() 中