2012-03-24 77 views
2

我在格式化从MySQL数据库接收到的日期时遇到问题。我不断收到此错误:PHP中的日期格式

Notice: A non well formed numeric value encountered in C:\xampp\htdocs\index.php on line 23 

这里是我的代码:

$news_query = $database->query("SELECT * FROM " . DB_NEWS . " ORDER BY 'date'"); 
    while($news_data = mysql_fetch_array($news_query,MYSQL_ASSOC)){ 
     $date = date("M d, Y - g:i:s A", $news_data['date']); 
     echo " 
     <DIV class = 'news_post'> 
      <DIV class = 'news_title'>" . $news_data['title'] . "</DIV> 
      <DIV class = 'news_info'>Posted on " . $date . " By " . $news_data["author"] . "</DIV> 
      <DIV class = 'entry'>" . $news_data['entry'] . "</DIV> 
     </DIV>"; 
    } 

我已经阅读过的时间戳PHP手册和日期功能,我似乎无法找出我的问题是。

+1

哪一行是第23行?赔率是'$ news_data ['date']'不是你认为的那样。 – j08691 2012-03-24 18:30:49

+0

mysql表中'date'的数据类型是什么? – safarov 2012-03-24 18:30:57

+0

第23行是这样的:$ date = date(“M d,Y - g:i:s A”,$ news_data ['date']);该类型是使用CURRENT_TIMESTAMP的时间戳。 – legobear154 2012-03-24 18:31:40

回答

3

您是否在MySQL中使用日期时间格式?

试试这个:

<?php 
    date("M d, Y - g:i:s A", strtotime($news_data['date'])); 
?> 
+0

谢谢!这工作!我必须等6分钟才能将其标记为答案。 – legobear154 2012-03-24 18:37:09

0

尝试此查询

$database->query("SELECT *,unix_timestamp(date) as date 
        FROM ".DB_NEWS." ORDER BY date") 
2

$news_data['date']的数据库中的日期可能是日期的字符串表示。 date()函数采用格式字符串和可选的时间戳,该时间戳是一个整数。这是你得到错误的原因。

1

最有可能的,strtotime()将您的日期转换成date()所需的格式。

相反的:

$date = date("M d, Y - g:i:s A", $news_data['date']) 

你想:

$date = date("M d, Y - g:i:s A", strtotime($news_data['date'])) 
0

有两种可能性。 第一个是:在你的查询中使用UNIXTIMESTAMP sql函数,或者像前面所说的strtotime。 第二,我更喜欢使用DateTime PHP对象。

$date = new DateTime($datas['date']); 
//if an error occurs because of the format use createFromFormat 
$date = DateTime::createFromFormat('d-m-y',$datas['date']);//for exemple for dd-mm-YYYY format