Cannot get around this error: calling the undefined method DateTime :: createFromFormat ()

I am trying to convert date formats to php.

The following code creates persistent errors

$myDate = "31/12/1980"; $myDateTime = DateTime::createFromFormat('d/m/Y', "$myDate"); $newDate = $myDateTime->format('d M Y'); echo $newDate; 

The line containing createFromFormat () continues to generate an error: "method call undefined". This happens both with my Apache test server, and with the actual server, as with PHP 5.3 +

Do I need to include or require additional files? Please help - I'm just a low level in php.

+4
source share
3 answers

Only two possible reasons why you should get this error:

  • You are not actually using PHP 5.3+, so the method does not exist. Double check the version of PHP your code is running on. You may have problems configuring your web server. If this is true and you cannot change it, see PHP DateTime::createFromFormat in 5.2? for alternatives.
  • You are in the namespace and should name it as \DateTime::createFromFormat(...) .
+4
source

This usually happens if the method cannot be found, which means that you did not include the file containing this method. Can you send the code for DateTime :: createFromFormat?

-2
source

I have found a solution. The correct date conversion syntax is:

 $myDate = "01-12-1980"; $tempDate = date_create("$myDate"); $newDate = date_format($tempDate, 'j M Y'); echo "$newDate"; 

Outputs: December 1, 1980 (j removes the leading zero from the number of days instead of d)

Note:

 $newDate = date("d MY", strtotime($myDate)); 

will not work in this example, because the expected input format is mm / dd / yyyy, using any other format will lead to incorrect output dates

-2
source

All Articles