Calculate difference between two dates using Carbon and Blade

孤人 提交于 2019-11-26 16:48:51

问题


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

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);

And retrieving that on a Blade template

  // VIEW ON BLADE

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

回答1:


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.

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);

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);

And then in your Blade template:

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



回答2:


You code can be cleaned up and have the commented out code removed by doing:

<td>{{ $diff = Carbon\Carbon::parse($work['date'])->diffForHumans(Carbon\Carbon::now()) }} </td>



回答3:


Blade Template

A shorter code

{{ $diff = Carbon\Carbon::parse($data->last_updated)->diffForHumans() }}
.

Result : 6 minutes ago



来源:https://stackoverflow.com/questions/39508963/calculate-difference-between-two-dates-using-carbon-and-blade

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!