PHP DateTime :: createFromFormat behavoiur

Today, I came across something confusing for me with the behavior of the \DateTime::createFromFormat .

In my case, I have a string representing a date in the following m/Y (05/2017) format m/Y (05/2017) . When I want to convert a string to a DateTime object, I ran into the following problem:

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

When I unload the $date variable, the $date property inside is '2017-03-03 11:06:36.000000'

But if I add the date to the month $date = \DateTime::createFromFormat('d/m/Y', '01/02/2017'); , I will return the object with the correct date. (unfortunately, I cannot change the date format and add the day. It must be m / Y).

The fix I came up with is to associate the first day of the month with a date string, I have $date = '01/'.$dateString; , but I do not want to do this because it is hard-coded.

What is wrong here? Is there a createFromFormat function with information on how to create an object? I am very confused about this. Thanks for any help in advance!

+5
source share
2 answers

By default, PHP will populate missing date values ​​with current date / time data; So

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

will fill in the missing day value with the current date; and February 31st is an invalid date; it will move in March. Similarly, hours / minutes / seconds will be filled with missing time values ​​depending on the current time.

If you want to force to force the start of the month / time, change your mask using the leader !

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

This will fill in the missing day with the 1st month, and the time from 00:00:00

Alternatively, the final | will have the same effect

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

You cannot store partial dates, at least in a special date format that can be used for complex date calculations (nothing prevents you from creating your own MonthYear class). Therefore, when you create a DateTime() object with incomplete information, something should happen:

  • Crash
  • Use default values

PHP selects the second option and makes a decision inherited from the C language date library:

  • Suppose Missing Data Means Now
  • Try to fix automatically invalid dates that this algorithm can create.

In this case, Feb 2017 becomes 31 Feb 2017 (because "now" is 31 May 2017 ), and PHP follows this argument: February only had 28 days in the year 2017, but I have three more; the user will probably want to move these three extra days in March. Therefore, 3 Mar 2017 .

I see no reason to avoid hard coding 01 because, after all, It has strict coding (why on the first day of the month, and not the last or any other day?).

 $input = '05/2017'; $date = \DateTime::createFromFormat('d/m/Y', "01/$input"); 
0
source

Source: https://habr.com/ru/post/1268392/


All Articles