Skip to content
Advertisement

Why do I get error when try to convert Carbon to DateTime?

I am developing a Laravel project. I try to create a DateTime object by using Carbon. This is what I tried:

Carbon::createFromFormat('Y-m-d H:i:s', '2021-10-01T00:01:00')->toDateTime();

But my phpstan complains : Cannot call method toDateTime() on CarbonCarbon|false.

Why is this error? What is the correct way to convert Carbon to a DateTime object?

Advertisement

Answer

Your format is incorrect, so Carbon cannot create the time. You’re missing the T, which needs to be escaped.

Carbon::createFromFormat('Y-m-dTH:i:s', '2021-10-01T00:01:00')->toDateTime();
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement