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

Time:11-12

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?

CodePudding user response:

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();

CodePudding user response:

Carbon objects are already DateTime objects.

class Carbon extends \DateTime

You may want toDateTimeString, but if you really want a DateTime object, you've already got one, just with a little Carbon syntax sugar sprinkled on top.

If you really need a DateTime object, the ->toDate() function is what you're looking for.

https://carbon.nesbot.com/docs/

Return native DateTime PHP object matching the current instance.

CodePudding user response:

If PHPStan complains, that's because the static analysis (which does not execute the code) cannot determine the types properly. As Carbon extends DateTime, the PHP documentation can help for this method call:

Returns a new DateTime instance or false on failure.

So, to ensure that the code is sound in terms of static analysis, you need to split it up:

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

if (!$object instanceof Carbon) {
  throw new RuntimeException('could not parse date');
}

$object->toDateTime();

The difference: now, PHPStan can safely assume that $object is of type Carbon when toDateTime() is called


As others pointed out: running that code would also yield an error, as the date format you try to parse from and the input date do not match. But that is out of scope for PHPStan, which does not execute the code

  • Related