php - 碳 : displaying hours and minutes?

标签 php laravel frameworks

我最近一直在使用Carbon来显示人性化的时间字符串,但由于某种原因,我只能让它显示主要因素,例如,我有一个日期,它需要显示到该日期还有多长时间。例如,如果距离现在还有 6 天 4 小时 32 分钟,则当前仅显示“6 天”。

我将如何让它也显示小时数,可能还有分钟数?当它只给你几天的时候看起来有点可怕,很多人可能想知道更多的小时和秒?

我在 Carbon 文档中找不到任何关于此的内容。如果这甚至相关,我将在 laravel 5.3 View 中使用它。

这是我的代码:

{{ \Carbon\Carbon::createFromTimeStamp(strtotime($item->created_at))->diffForHumans() }}

最佳答案

你不应该使用 diffForHumans()在这种情况下,因为它只返回一个不能再处理的字符串。这是最终结果。

最好使用 Carbon对象,像这样:

$created = \Carbon\Carbon::createFromTimeStamp(strtotime($item->created_at));

然后,在 View 中添加:
{{ $created ->diff(\Carbon\Carbon::now())->format('%d days, %h hours and %i minutes'); }}

您可以延长更长的时间:
$created ->diff(\Carbon\Carbon::now())->format('%y year, %m months, %d days, %h hours and %i minutes');

编辑(根据评论):

如果你这样做:
$diff = $created->diff(Carbon::now());
var_dump($diff);

你得到这个结果:
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

从那里,您浏览元素以创建满足您需求的最佳答案。

关于php - 碳 : displaying hours and minutes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43952722/

相关文章:

php - 拉维尔 8 : Weird missing required parameter

javascript - 插入外部页面后更改所有href

php - 为什么 mysqli 给出 "Commands out of sync"错误?

php - 对每个组的用户有限制的预加载

php - 将链函数作为参数传递给 php 中的参数

Python 网络框架 + [a] 同步任务;长轮询 : not Django

ios - Xcode删除pod文件后如何删除框架

scala - 有没有什么好的 Scala 特定的框架和库值得一看?

php - 将隐藏的输入作为字符串抓取(使用 PHP 简单 HTML DOM 解析器)

php - 使用 $wpdb->prepare() 时出错