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

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

Laravel - Getting Current Month and Year only

phplaraveldatetime

提问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 datefunction. 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

请参阅有关日期函数的 PHP 文档

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 Carbonit have many method to access and modifie DateTimephp object. To access the month and year of the current day you can access the property monthand yeardirectly on the Carbon Object

Laravel 附带了一个预构建的组件来管理 Date,并且它知道在名称下Carbon它有许多方法来访问和修改DateTimephp 对象。要访问当天的月份和年份,您可以访问该属性monthyear直接在 Carbon 对象上访问

$today = Carbon::now();
$today->month; // retrieve the month
$today->year; // retrieve the year of the date

In you Controller you can pas the $todayobject 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') }}