PHP DateTime::createFromFormat behavoiur

date, datetime, php

Solution

By default, PHP will populate missing date values with those of the current date/time; so

$date = \DateTime::createFromFormat('m/Y', '02/2017');

will populate the missing day value with the current date; and as 31st February is an invalid date, it will roll forward into March. Likewise, hours/minutes/seconds will be populated with the missing time values based on the current time.

If you want to force the behaviour of forcing to the beginning of the month/time, then modify your mask with a leading `!`

$date = \DateTime::createFromFormat('!m/Y', '02/2017');

This will populate the missing day with the 1st of the month, and the time with `00:00:00`

Alternatively, a trailing `|` will have the same effect

$date = \DateTime::createFromFormat('m/Y|', '02/2017');

Problem

Today I've encountered something confusing for me with the behaviour of the `\DateTime::createFromFormat` function. In my case I have a string, representing the date in the following format `m/Y (05/2017)`. When I want to convert the string to DateTime object I've encountered the following issue: `$date = \DateTime::createFromFormat('m/Y', '02/2017');` When I dump the `$date` variable, the date property inside is `'2017-03-03 11:06:36.000000'` But if I add the date before the month `$date = \DateTime::createFromFormat('d/m/Y', '01/02/2017');` I get back an object with correct date property. (unfortunately I cant change the format of the date and add the day. It must be m/Y). The fix I've come up with is to concatenate the first day of the month to the date string I have `$date = '01/'.$dateString;` but I rather not to do that because it's hardcoded. What is wrong here? Does the createFromFormat function lack information of how to create the object? I'm quite confused with this. Thanks for everyone's help in advance!

Original source