CoderSte CoderSte - 25 days ago 13
PHP Question

Uncaught exception 'Exception' with message 'DateTime::__construct():

I have a problem outputting the date which is created within my

PHP
file.

I've been following a tutorial on how to make a really Basic-CMS Platform to help me understand some of the basics for
databases
and
PHP
, everything has been going well up until I was trying to output the date of when the page was created.

This is the error I get

Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): It is not safe to rely on the system's timezone settings.
You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of
those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone.' in
C:\MAMP\htdocs\basic-cms\page.php:22 Stack trace: #0 C:\MAMP\htdocs\basic-cms\page.php(22): DateTime->__construct('2016-02-17 10:3...') #1 {main} thrown in C:\MAMP\htdocs\basic-cms\page.php on line 22


Now when I remove line 22 inside my
page.php
it outputs the full date that is inside the database
i.e - 2016-02-17 10:38:05
but I'm trying to format it to show the date like
jS M, Y
.

This is the code within my
page.php
file

if ( $page ) {
$page['created'] = new DateTime( $page['created'] );

if ( $page['updated'] ) {
$page['updated'] = new DateTime( $page['created'] );
}
}


Then inside my
show.php
where I'm displaying this I have this code to format the date.

Created on <?php echo $page['created']->format('jS M, Y'); ?>


Now removing this from my
show.php
doesn't do anything as that's not where the error is contained - but I thought I'd show you guys what I am trying to achieve.

Like I said this is a very Basic-CMS site that I am creating by following a tutorial on YouTube and I have copied his code exactly and he got no error so I'm sure it has to be a typo I just can't find.

Answer

This is because no timezone has set in php configuration.

Add the following line of code to top of your php.ini file

date.timezone = "US/Central"

And restart web server

OR

you can set it via php script also by using following function:

date_default_timezone_set('America/Los_Angeles');

Dont forget to reload/restart apache server

Comments