php Laravel - 如何获得日期的年份属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34202965/
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 - How to get year property of date
提问by ketom
I have a "datetime" field in mysql.
我在 mysql 中有一个“日期时间”字段。
$time = "1900-01-01 00:00:00";
I cant get only year.
I tried $time -> year
, but its not good.
我不能只得到一年。我试过了$time -> year
,但效果不好。
(Trying to get property of non-object) Maybe i need to convert this string to date?
(试图获取非对象的属性)也许我需要将此字符串转换为日期?
I hope someone can help me! Thanks so much!
我希望有一个人可以帮助我!非常感谢!
回答by Kalhan.Toress
You can do this in two ways,
你可以通过两种方式做到这一点,
1 - Define the date filed in the related model
as,
1 - 定义在相关文件中提交的日期model
,
public function getDates()
{
//define the datetime table column names as below in an array, and you will get the
//carbon objects for these fields in model objects.
return array('created_at', 'updated_at', 'date_time_field');
}
then laravel return a carbon object for these columns, so that you can use like $time->year
.
然后 Laravel 为这些列返回一个 carbon 对象,以便您可以使用 like $time->year
。
2- You can create a carbon object and get the year as in Moppo's answer
2-您可以创建一个碳对象并按照 Moppo 的回答获取年份
Carbon::createFromFormat('Y-m-d H:i:s', $time)->year
First one make so clean for me, you can decide which way suits you.
第一个对我来说很干净,你可以决定哪种方式适合你。
回答by Moppo
回答by ShaneMit
use PHP's built in methods
使用 PHP 的内置方法
$year = date('Y', strtotime($dateString));
回答by AdiechaHK
Try out this one
试试这个
$time = date_create("2014-01-01 00:00:00");
echo date_format($time, 'Y');
回答by dipenparmar12
Get year
, month
and day
from timestamp date using carbon library in Laravel.
获取year
,month
并day
使用碳库Laravel时间戳日期。
- Get Year
- 获取年份
$timestemp = "2020-01-01 01:02:03";
$year = Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $timestemp)->year;
- Get Month
- 获取月份
$timestemp = "2020-01-01 01:02:03";
$month = Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $timestemp)->month;
- Get day
- 得到一天
$timestemp = "2020-01-01 01:02:03";
$day = Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $timestemp)->day;