Laravel - 仅获取当前月份和年份
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53386547/
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
Laravel - Getting Current Month and Year only
提问by Sheetal Mehra
I am new to Laravel I'm just learning new things, but as for my project. I need to get the current month and year for today. How can I do it? for what I have now is a label and I want to put the current month and year on the label. Thank you
我是 Laravel 的新手,我只是在学习新事物,但至于我的项目。我需要获取今天的当前月份和年份。我该怎么做?因为我现在拥有的是一个标签,我想把当前的月份和年份放在标签上。谢谢
Here is my LABEL
这是我的标签
{{Form::label('title', 'Title')}}
回答by Angad Dubey
You can use the Carbonlibrary which is available out of the box with Laravel:
您可以使用Laravel 开箱即用的Carbon库:
{{ Form::label('title', \Carbon\Carbon::now()->format('M, Y') }}
You can format using native PHP DateTime Format
您可以使用本机 PHP 日期时间格式进行格式化
Update:
更新:
As @Josh mentioned, you can also use the laravel helper now()
正如@Josh 提到的,你也可以使用 laravel 助手now()
The now function creates a new Illuminate\Support\Carbon instance for the current time
now 函数为当前时间创建一个新的 Illuminate\Support\Carbon 实例
{{ Form::label('title', now()->format('M, Y') }}
回答by hktang
If you want to always display the current day's month and year, you can use PHP's built-in date
function. For example, the below will give you a label November 2018
.
如果想一直显示当天的月份和年份,可以使用PHP的内置date
函数。例如,下面会给你一个标签November 2018
。
{{Form::label('title', date('F Y') )}}
See PHP Documentation on the date function
If you want more powerful manipulation, use Carbon.
如果您想要更强大的操作,请使用Carbon。
回答by Yves Kipondo
Laravel come with a prebuilt component to manage Date, and it's know under the name Carbon
it have many method to access and modifie DateTime
php object. To access the month and year of the current day you can access the property month
and year
directly on the Carbon Object
Laravel 附带了一个预构建的组件来管理 Date,并且它知道在名称下Carbon
它有许多方法来访问和修改DateTime
php 对象。要访问当天的月份和年份,您可以访问该属性month
并year
直接在 Carbon 对象上访问
$today = Carbon::now();
$today->month; // retrieve the month
$today->year; // retrieve the year of the date
In you Controller you can pas the $today
object to the method use to render the related view with purpose to have access to that object on a get value of attribute that you want to show in the label field
在您的 Controller 中,您可以将$today
对象传递给用于呈现相关视图的方法,目的是在要在标签字段中显示的属性的获取值上访问该对象
回答by Sheetal Mehra
You can also try this.
你也可以试试这个。
{{ Form::label('title', Carbon\Carbon::now()->format('F Y') }}