Laravel - How to get year property of date
Asked Answered
V

5

16

I have a "datetime" field in mysql.

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

I cant get only year. I tried $time -> year, but its not good.

(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!

Voltcoulomb answered 10/12, 2015 at 13:18 Comment(0)
D
20

You can do this in two ways,


1 - Define the date filed in the related model as,

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.


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

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

First one make so clean for me, you can decide which way suits you.

Deyo answered 10/12, 2015 at 13:35 Comment(0)
C
18

In Laravel you can use Carbon to parse the date:

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

Once you get the Carbon object, to get the year you can do:

$date->year;

Or:

$date->format('Y');
Coal answered 10/12, 2015 at 13:25 Comment(0)
L
10

use PHP's built in methods

$year = date('Y', strtotime($dateString));
Lanta answered 9/12, 2016 at 16:47 Comment(0)
T
4

Try out this one

$time = date_create("2014-01-01 00:00:00");
echo date_format($time, 'Y');
Tetreault answered 10/12, 2015 at 13:44 Comment(0)
D
2

Get year, month and day from timestamp date using carbon library in Laravel.

  1. Get Year
$timestemp = "2020-01-01 01:02:03";
$year = Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $timestemp)->year;
  1. Get Month
$timestemp = "2020-01-01 01:02:03";
$month = Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $timestemp)->month;
  1. Get day
$timestemp = "2020-01-01 01:02:03";
$day = Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $timestemp)->day;
Dalesman answered 10/4, 2020 at 19:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.