【问题标题】:Carbon difference of now() vs datetime with "ago" using diffForHumans() method使用 diffForHumans() 方法的 now() 与日期时间与“之前”的碳差异
【发布时间】:2015-11-27 06:33:27
【问题描述】:

根据手册:http://carbon.nesbot.com/docs/#api-humandiff

获取ago

将过去的值与现在的默认值进行比较时

但无论我做什么,我都无法获得ago

return $datetime->diffForHumans(Carbon::now())

结果到before,而

return Carbon::now()->diffForHumans($datetime);

结果到after

但是您可以清楚地看到,我上面的两个 sn-p 都比较了 past($datetime) 和现在的默认值 (Carbon::now()) 所以我不明白为什么我不能得到一个前?希望有人可以提供帮助。我只需要回显ago。谢谢!

【问题讨论】:

    标签: php datetime php-carbon


    【解决方案1】:

    您应该在“日期计算”之后使用不带参数的diffForHumans(),例如:

    Carbon::now()->subDays(24)->diffForHumans();  // "3 weeks ago"
    

    或者,如果你有约会,你可以使用 $datetime->diffForHumans();

    $datetime = Carbon::createFromDate(2015, 8, 25); // or your $datetime of course
    return $datetime->diffForHumans();  // "1 week ago"
    

    【讨论】:

      【解决方案2】:

      虽然@baao 给出了很好的答案,但如果您传递原始日期输入,例如 Laravels created_atCarbon::createFromDate() 函数可能会出现问题。现在您必须使用不同的功能。看看下面吧。

      $carbondate = Carbon::parse($users->created_at); 
      $past = $carbondate->diffForHumans();
      dd($past);
      

      其中 $users->created_at 是类似 2018-05-03 14:54:14 的日期,然后会给出 2 周前的答案。

      【讨论】:

      • Laravel 提供 created_at 作为 Carbon 实例,所以实际上你可以简单地调用 $model->updated_at->diffForHumans();
      猜你喜欢
      • 2019-05-04
      • 2016-06-22
      • 1970-01-01
      • 1970-01-01
      • 2018-11-20
      • 1970-01-01
      • 2016-10-06
      • 1970-01-01
      • 2016-08-14
      相关资源
      最近更新 更多