5

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.

user2157155
  • 167
  • 1
  • 2
  • 6

3 Answers3

5

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(...).
Community
  • 1
  • 1
deceze
  • 510,633
  • 85
  • 743
  • 889
-2

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?

Elmir Kouliev
  • 77
  • 1
  • 12
-2

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

user2157155
  • 167
  • 1
  • 2
  • 6
  • What you're doing is exactly the same as `date("j M Y", strtotime($myDate))`, only using the procedural interface of the `DateTime` class. It's in no way equivalent to `DateTime::createFromFormat`. – deceze Apr 18 '13 at 04:31