Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MattB's avatar
Level 2

DateTime::__construct(): Failed to parse time string (02-2020) at position 0 (0): Unexpected character

I'm storing just a month and year in my db which stores it as a string such as this for example:

02-2020

I'm trying to turn it into a month and date using carbon so hopefully it looks like this:

February 2020

I'm using this line of code to do it:

{{ $newsflash->date->createFromFormat('MM YYYY') }}

But get error

DateTime::__construct(): Failed to parse time string (02-2020) at position 0 (0): Unexpected character

I'm not sure what's happening, or what the character is I'm messing up with. Any help would be massively appreciated. I do have the following in my model which allows it to be manipulated:

protected $dates = ['date'];
0 likes
5 replies
Snapey's avatar

your string has a hyphen, and you need to use the php formatting chars

02-2020

{{ $newsflash->date->createFromFormat('m-Y') }}

this will cast it to a Carbon instance, which you can then format

{{ $newsflash->date->createFromFormat('m-Y')->format('F Y') }}

probably one for an accessor if $newsflash is a model

https://newcircleconsulting.com/2007/11/php-data-format-cheat-sheet/

edit: Just saw that you have already cast it to a Carbon instance in the model, so just;

{{ $newsflash->date->format('F Y') }}
MattB's avatar
Level 2

Sorry, no joy. Seems like the problem might be in the model with this possibly?:

protected $dates = ['date'];
MattB's avatar
Level 2

Sadly no. I'm storing the date as a string in the db, not a date format. Is that the issue here? I'm converting it with

protected $dates = ['date'];

Have I done something wrong there?

Snapey's avatar

if it is not a date column in the database then you cannot just cast it in the model as Eloquent has no clue what the string represents.

If you can, go back and change the column type and store it as a date (you will also need a day, although you don't have to display this anywhere)

If not, create a model accessor

Please or to participate in this conversation.