laravel 碳:显示小时和分钟?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43952722/
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
Carbon: displaying hours and minutes?
提问by Ash Smith
I have recently been using Carbon to display humanized time strings, but for some reason I can only get it to show the main factor, for example, I have a date that it needs to show how long until that date is. So for example, if its 6 days, 4 hours and 32 minutes away from now, it currently only displays '6 days'.
我最近一直在使用Carbon来显示人性化的时间字符串,但由于某种原因,我只能让它显示主要因素,例如,我有一个日期,它需要显示到该日期还有多长时间。例如,如果距离现在还有 6 天 4 小时 32 分钟,则当前仅显示“6 天”。
How would I go about getting it to display the hours too, and possibly the minutes? It's kind of horrible looking when it only gives you the days, and many people may want to know more like the hours and seconds?
我将如何让它也显示小时数,可能还有分钟数?当它只给你几天的时候看起来有点可怕,很多人可能想知道更多的小时和秒?
I can't find anything on the Carbon documentation for this. I am using it inside a laravel 5.3 view if that's even relevant.
我在 Carbon 文档中找不到任何关于此的内容。如果这甚至相关,我将在 laravel 5.3 视图中使用它。
Heres my code:
这是我的代码:
{{ \Carbon\Carbon::createFromTimeStamp(strtotime($item->created_at))->diffForHumans() }}
回答by w3spi
You shouldn't use diffForHumans()
in this case, because it returns only a string on which one can no longer work. This is an end result.
diffForHumans()
在这种情况下你不应该使用,因为它只返回一个不能再使用的字符串。这是最终结果。
It is better to work with a Carbon
object, like this :
最好使用一个Carbon
对象,如下所示:
$created = \Carbon\Carbon::createFromTimeStamp(strtotime($item->created_at));
And then, add this in the view :
然后,在视图中添加:
{{ $created ->diff(\Carbon\Carbon::now())->format('%d days, %h hours and %i minutes'); }}
You can extend for a larger period :
您可以延长更长的时间:
$created ->diff(\Carbon\Carbon::now())->format('%y year, %m months, %d days, %h hours and %i minutes');
EDIT (according to the comments) :
编辑(根据评论):
If you do :
如果你这样做:
$diff = $created->diff(Carbon::now());
var_dump($diff);
You get this result :
你得到这个结果:
object(DateInterval)[113]
public 'y' => int 0
public 'm' => int 0
public 'd' => int 6
public 'h' => int 4
public 'i' => int 32
public 's' => int 29
public 'f' => float 0.397424
public 'weekday' => int 0
public 'weekday_behavior' => int 0
public 'first_last_day_of' => int 0
public 'invert' => int 0
public 'days' => int 6
public 'special_type' => int 0
public 'special_amount' => int 0
public 'have_weekday_relative' => int 0
public 'have_special_relative' => int 0
// results depend of the current time
From there, you browse the elements to create the best answer to your needs.
从那里,您浏览元素以创建满足您需求的最佳答案。