Laravel - How to Get Property for a Year

I have a "datetime" field in mysql.

$time = "1900-01-01 00:00:00";

I can’t get only a year. I tried $time -> year, but it is not good.

(Trying to get a non-object property) Maybe I need to convert this string to date?

Hope someone can help me! Many thanks!

+4
source share
4 answers

You can do this in two ways:


1 - Define the date indicated in the corresponding modelas,

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 returns the carbon object for these columns, so you can use like $time->year.


2- You can create a carbon object and get a year, as in Moppo's answer

Carbon::createFromFormat('Y-m-d H:i:s', $time)->year

, , .

+5

Laravel Carbon :

$time = "1900-01-01 00:00:00";
$date = new Carbon( $time );   

Carbon, , :

$date->year;

:

$date->format('Y');
+3

Try this one

$time = date_create("2014-01-01 00:00:00");
echo date_format($time, 'Y');
+2
source

use PHP built-in methods

$year = date('Y', strtotime($dateString));
+2
source

Source: https://habr.com/ru/post/1619360/


All Articles