Search code examples
phplaravelphp-carbonphpstan

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 Carbon\Carbon|false.

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


Solution

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

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