How are 'c' or 'r' date format working in PHP?

Viewed 1370

I've tried to format some date using 'c' or 'r' format and I ended up having weird results.

I've tried the PHP interpreter from my personal computer or using the php:latest Docker image.

Along the way, I've tried many methods and even the results of these ones surprised me.

var_dump(DateTime::createFromFormat('c', (new DateTime())->format('c'))); // false
// or
var_dump(DateTime::createFromFormat('r', (new DateTime())->format('r'))); // false

(new DateTime())->format('c') returns a string in the expected format but I thought creating a DateTime object from it would return a valid object and not false.

What's this behavior ?

Thanks for your help :)

1 Answers

Those format characters are unknown as per documentation, where it's also stated (emphasis mine):

$format The format that the passed in string should be in. See the formatting options below. In most cases, the same letters as for the date() can be used.

You can call DateTime::getLastErrors() to see more (though slightly confusing) details:

Array
(
    [warning_count] => 0
    [warnings] => Array
        (
        )

    [error_count] => 2
    [errors] => Array
        (
            [0] => The format separator does not match
            [1] => Trailing data
        )

)
Related