PHP DateTime::createFromFormat behavoiur

Viewed 1327

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!

2 Answers
Related