php 使用 Carbon 和 Blade 计算两个日期之间的差异
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39508963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculate difference between two dates using Carbon and Blade
提问by iivannov
Does anyone know how to pass a given variable instead the Carbon's default parameters ?
有谁知道如何传递给定的变量而不是 Carbon 的默认参数?
The documentation of Carbon says:
Carbon的文档说:
// 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
并在 Blade 模板上检索它
// VIEW ON BLADE
<td> {{ $testdate }} </td>
回答by iivannov
You are not following the example from the Carbon Documentation. The method Carbon::createFromDate()
expects 4 parameters: year, month, dayand timezone. And you are trying to pass a formatted date string.
您没有遵循Carbon 文档中的示例。该方法Carbon::createFromDate()
需要 4 个参数:year、month、day和timezone。并且您正在尝试传递格式化的日期字符串。
If you want to create a Carbon object from a formatted date string you can use the constructor of the class just like this:
如果你想从格式化的日期字符串创建一个 Carbon 对象,你可以像这样使用类的构造函数:
$date = "2016-09-17 11:00:00";
$datework = new Carbon($date);
Or you can use the static Carbon::parse()
method:
或者您可以使用静态Carbon::parse()
方法:
$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:
然后在你的 Blade 模板中:
<td> {{ $diff }} </td>
回答by Stephen S
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>
回答by CodeGuru
Blade Template
刀片模板
A shorter code
更短的代码
{{ $diff = Carbon\Carbon::parse($data->last_updated)->diffForHumans() }}
.
Result : 6 minutes ago
结果 : 6 分钟前