Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP PHP Standards and Best Practices Databases and International Concerns Working with DateTime

Placid Rodrigues
Placid Rodrigues
12,630 Points

Getting Fatal Error: Call to a member function format() on a non-object

Hi, I am getting Fatal Error in the browser when I test the following code as shown in lecture:

<?php

$raw = '10 . 11 . 1968';
$date = DateTime::createFromFormat('d . m. Y', $raw);

?>
<p>The output date is: <?php echo $date->format("m/d/Y"); ?> </p>

The Fatal Error is: Fatal error: Call to a member function format() on a non-object in C:\wamp\www\tt\tt_php_best_practices\date_time.php on line 14

Can anyone please tell me how to solve the issue?

Thanks,

Placid

1 Answer

Jose Soto
Jose Soto
23,407 Points

You're just missing a space after the 'm' character. The CreateFromFormat method of the DateTime object will read the format exactly as it is entered. If it can't create a new DateTime object from that string, then it returns a bool false.

This should work:

<?php

$raw = '10 . 11 . 1968';
$date = DateTime::createFromFormat('d . m . Y', $raw);

?>

<p>The output date is: <?php echo $date->format("m/d/Y"); ?> </p>
Placid Rodrigues
Placid Rodrigues
12,630 Points

Thanks Jose for clear explanation.