带有消息'DateTime :: __ construct()的未捕获异常'Exception':

时间:2016-02-17 11:23:36

标签: php datetime

输出在PHP文件中创建的日期时出现问题。

我一直在关注如何创建一个真正的基础CMS平台的教程,以帮助我理解databasesPHP的一些基础知识,一切都进展顺利,直到我尝试输出创建页面的日期。

这是我得到的错误

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

现在当我删除page.php内的第22行时,它会输出数据库中的完整日期,即2016-02-17 10:38:05,但我正在尝试对其进行格式化以显示jS M, Y (17th Feb 2016)之类的日期

这是我的page.php文件

中的代码
if ( $page ) {
    $page['created'] = new DateTime( $page['created'] );

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

然后在我显示的show.php里面,我有这个代码来格式化日期。

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

现在从我的show.php删除它并没有做任何事情,因为那不是包含错误的地方 - 但我想我会向你们展示我想要实现的目标。

就像我说这是一个非常基本的CMS网站,我正在通过跟随tutorial on YouTube创建并且我已经完全复制了他的代码并且他没有错误所以我确定它必须是一个错字我只是找不到。

2 个答案:

答案 0 :(得分:8)

这是因为在php配置中没有设置时区。

将以下代码行添加到php.ini文件的顶部

date.timezone = "US/Central"

重新启动网络服务器

您也可以使用以下功能通过php脚本进行设置:

date_default_timezone_set('America/Los_Angeles');

别忘了重装/重启apache服务器

答案 1 :(得分:0)

如果您在创建页面详细信息时使用数据库来保存页面详细信息:

您实际上只需在数据库中添加DateTime列,然后在创建页面并插入需要添加的内容时,将列设置为默认TimeStamp,它应自动添加创建页面的时间和日期你。

然后从数据库中获取TimeStamp(MySQLi版本):

$db = mysqli_connect('host', 'user', 'pass', 'dbname');
$result = $db->query("SELECT * FROM tbl_name");
// add an error check here
while($row = mysqli_fetch_array($result)){
   if($row['columnPageID'] == 'the page ID you are on'){
       $createdOn = $row['columnName'];
   }
}
$db->close();

此代码将工作,因此您可以理解。