如何在 Laravel 5.2 应用程序中使用 carbon

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35999711/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:24:45  来源:igfitidea点击:

How use carbon in Laravel 5.2 application-wide

phplaravelphp-carbon

提问by jahsen

How to use Carbon in Laravel 5.2 without use Carbon\Carbon;added in every View and Controller..?

如何在 Laravel 5.2 中使用 Carbon 而不use Carbon\Carbon;在每个视图和控制器中添加..?

回答by zsolt.k

Add the following line to the aliases array in the config/app.php:

将以下行添加到 config/app.php 中的 aliases 数组:

'Carbon' => 'Carbon\Carbon'

And you need to add use Carbon;every class where you want to use it.

并且您需要将use Carbon;每个类添加到您想要使用它的地方。

回答by Hammerbot

You can declare some fields in your models using the following structure:

您可以使用以下结构在模型中声明一些字段:

protected $dates = ['created_at', 'updated_at', 'disabled_at','mydate'];

All of those fields will automatically be Carbon instances and you will be able to use them in your views like:

所有这些字段都将自动成为 Carbon 实例,您将能够在您的视图中使用它们,例如:

{{ $article->mydate->diffForHumans() }}

This is the answer I provided some time ago here.

这是我前段时间在这里提供的答案。

And hereis the documentation from Laravel for that

这里是Laravel文档为

回答by kapitan

Here's what I have on my helpers.php

这是我在 helpers.php 上的内容

function myCarbon($date)
{
  return $date != '' ? \Carbon\Carbon::parse($date) : '-';
}

Then on any controllers and views:

然后在任何控制器和视图上:

myCarbon($model->field)->format('F d, Y');

And since I usually have mm/dd/yyyyand mm/dd/yyyy H:ion my blades, I have these on my helper file:

因为我通常在刀片上有mm/dd/yyyymm/dd/yyyy H:i,所以我的帮助文件中有这些:

function mydateFormat($date)
{
  return $date != '' ? myCarbon($date)->format('m/d/Y') : '-';
}

function mytimeFormat($date)
{
  return $date != '' ? myCarbon($date)->format('H:i') : '-';
}

function mydateTime($date)
{
  return $date != '' ? myCarbon($date)->format('m/d/Y H:i') : '-';
}

Now you can use this application-wide on any controllers and views.

现在您可以在任何控制器和视图上使用这个应用程序范围。

(note: function names are sample only, not what actually I am using, change based on your need)

(注意:函数名只是示例,不是我实际使用的,根据您的需要更改)