PHP DateTimeImmutable::createFromFormat Reset Character
I was recently building something that was taking date input from an HTML form field, and casting it to a PHP DateTimeImmutable. I was then comparing that to another date, and got thrown off during testing when I compared the resulting instance to new DateTimeImmutable('today'); the instances were not considered equal.
To recreate the conditions, you can try the following:
$date = '2016-06-16';
$fromForm = DateTimeImmutable::createFromFormat('Y-m-d', $date);
$today = new DateTimeImmutable('today');
echo $fromForm == $today ? 'Equal' : 'Not equal'; // outputs "Not equal"
What's happening? Well, if you were to echo the results of each of $fromForm->format('c') and $today->format('c'), the difference is clear: the $fromForm value includes the time when the instance was created, while $today has the time set to midnight.
So, how do you zero out the time when using createFromFormat()?
It turns out that one of the format characters you can use is the | operator. When you include this at the end of your format string, any fields not included in the format are zero'ed out:
$fromForm = DateTimeImmutable::createFromFormat('Y-m-d|');