Cátia Matos
Cátia Matos

Reputation: 930

Can not extract year with DateTime::createFromFormat

I'm trying to extract the year of a input date like

$start = $request->input('start');

$refYear = DateTime::createFromFormat("Y-m-d H:i:s", $start)->format("Y");

But I'm having the error Call to a member function format() on boolean and i saw another answers but nothing result so far.

Where start is defined as a input in my page

<input id="start" type="text" name="start" class="date-type"
                placeholder="dd-mm-aaaa"><i class="fi-calendar" style="top: 2px;"></i>

In my table the startDate column is a date time like '2017-10-26 00:00:00.000' and refyear is a int (2017).

Upvotes: 0

Views: 58

Answers (2)

Blackbam
Blackbam

Reputation: 19366

According to the documentation DateTime::createFromFormat:

Returns a new DateTime instance or FALSE on failure.

This is why you call it on a boolean, because the value is false.

Your format seems to be correct, that means createFromFormat can not handle your $start . Your input does not match your format, make sure it matches.

The following for instance works:

echo (DateTime::createFromFormat("Y-m-d H:i:s", "2019-01-01 12:30:30"))->format("Y"); // result: 2019

@jeprubio from the comments is right btw. - add the milliseconds to match your given format:

echo DateTime::createFromFormat("Y-m-d H:i:s.u", "2017-10-26 00:00:00.000")->format("Y"); // 2017

Upvotes: 1

nakov
nakov

Reputation: 14268

You can try to use Carbon instead:

$refYear = Carbon::createFromFormat("Y-m-d H:i:s", $start)->format("Y");

But also your format is wrong you are missing .u based on your example of the date field. You should use this:

$refYear = Carbon::createFromFormat("Y-m-d H:i:s.u", $start)->format("Y");

Upvotes: 0

Related Questions