使用Carbon和Blade计算两个日期之间的差异

使用Carbon和Blade计算两个日期之间的差异

本文介绍了使用Carbon和Blade计算两个日期之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道如何传递给定变量而不是Carbon的默认参数吗?

Does anyone know how to pass a given variable instead the Carbon's default parameters ?

Carbon的文档说:

The documentation of Carbon says:

// CARBON SAMPLE

$dtToronto = Carbon::createFromDate(2012, 1, 1, 'America/Toronto');
$dtVancouver = Carbon::createFromDate(2012, 1, 1, 'America/Vancouver');
echo $dtVancouver->diffInHours($dtToronto); // 3

我想在控制器中执行以下操作:

And i want to do something like this in my controller:

  // EXAMPLE

  $date = "2016-09-16 11:00:00";
  $datework = Carbon::createFromDate($date);
  $now = Carbon::now();
  $testdate = $datework->diffInDays($now);

并在Blade模板上检索

And retrieving that on a Blade template

  // VIEW ON BLADE

  <td> {{ $testdate }} </td>

推荐答案

您没有遵循 Carbon中的示例文档.方法Carbon::createFromDate()需要4个参数:时区.而且您正在尝试传递格式化的日期字符串.

You are not following the example from the Carbon Documentation. The method Carbon::createFromDate() expects 4 parameters: year, month, day and timezone. And you are trying to pass a formatted date string.

如果要从格式化的日期字符串创建Carbon对象,可以使用该类的构造函数,如下所示:

If you want to create a Carbon object from a formatted date string you can use the constructor of the class just like this:

$date = "2016-09-17 11:00:00";
$datework = new Carbon($date);

或者您可以使用静态Carbon::parse()方法:

Or you can use the static Carbon::parse() method:

$date = "2016-09-17 11:00:00";
$datework = Carbon::parse($date);

出于您的目的,您可以使用以下完整示例:

For your purposes you can use the this full example:

$date = Carbon::parse('2016-09-17 11:00:00');
$now = Carbon::now();

$diff = $date->diffInDays($now);

然后在您的Blade模板中:

And then in your Blade template:

<td> {{ $diff }} </td>

这篇关于使用Carbon和Blade计算两个日期之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 09:59