3

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 :)

hunomina
  • 332
  • 3
  • 13
  • `$t = new DateTime(); echo $t->format('c'); // 012345` this is enough, I think you are complicating things – Rahul Jun 21 '19 at 13:58
  • I'm trying to check user inputs in my project, not just create an object from the void. That's why I'm using `DateTime::createFromFormat()` to check if the user input match the date format. – hunomina Jun 21 '19 at 14:02

1 Answers1

1

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
        )

)
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
  • Thank you ! I was looking at the wrong documentation >_< I was reading the `date()` documentation (https://www.php.net/manual/fr/function.date.php) :/ Thank you again :D – hunomina Jun 21 '19 at 15:15