使用 Carbon 和 Blade 计算两个日期之间的差异 [英] Calculate difference between two dates using Carbon and Blade

查看:31
本文介绍了使用 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 个参数:yearmonthdaytimezone.而您正试图传递一个格式化的日期字符串.

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 计算两个日期之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆