user2157155
user2157155

Reputation: 187

Can't get around this error: Call to undefined method DateTime::createFromFormat()

I am trying to convert date formats in 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() keeps creating the error: " "call to undefined method". This occurs both with my testing Apache server and the actual server, both running PHP 5.3+

Do I need to include or require additional files? Please help - I am only a low-intermediate in php.

Upvotes: 5

Views: 8253

Answers (3)

deceze
deceze

Reputation: 522210

The only two possible reasons why you should be getting this error are:

  1. You're not in fact using PHP 5.3+, so that method does not exist. Double check what PHP version your code is running on. Maybe you have an oops in your web server configuration. If that is indeed so and you cannot change it, see PHP DateTime::createFromFormat in 5.2? for alternatives.
  2. You're in a namespace and need to call it like \DateTime::createFromFormat(...).

Upvotes: 5

user2157155
user2157155

Reputation: 187

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

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

Produces output: 1 Dec 1980 (j instead of d removes the leading zero from the day number)

Please note that:

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

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

Upvotes: -2

Elmir Kouliev
Elmir Kouliev

Reputation: 87

This usually occurs if the method cannot be found, meaning you haven't included the file that contains this method. Can you post code for DateTime::createFromFormat?

Upvotes: -2

Related Questions