2012-04-16 81 views
0

我有一个查询返回一个日期,我想在我的页面显示给用户之前格式化它。但是,当我使用格式时,日期显示为空(显示1969年)。这里是获取数据的代码:从mysqli返回的PHP格式日期

$sql = 'SELECT u.username, td.postingText, td.createdOn, td.lastUpdated 
     FROM threadDetails td, users u 
     WHERE blogThreadId = ? 
     AND td.userId = u.userId 
     order by td.createdOn DESC'; 
$stmt = $conn->stmt_init(); 
$stmt->prepare($sql); 
$stmt->bind_param('s', $blogThreadId); 
$stmt->bind_result($username, $postingText, $createdOn, $lastUpdated); 
$stmt->execute(); 
$stmt->store_result(); 

$numrows = $stmt->num_rows; 
while ($stmt->fetch()) 
{ 
    $rowofdata=array(
     'username' => $username, 
     'postingText' => $postingText, 
     'createdOn' => $createdOn, 
     'lastUpdated' => $lastUpdated, 
    ); 
    $results[] = $rowofdata; 
} 
$stmt->close(); 

当我把它打印出来用下面的代码(在不同的功能):

foreach ($threadData as $threadDetailItem) 
{ 
    $msg = sprintf ("<tr>%s %s %s %s %s </tr>\n", 
     "<td>" . $threadDetailItem['threadTitle'] . "</td>", 
     "<td>" . $threadDetailItem['username'] . "</td>", 
     "<td>" . $threadDetailItem['createdOn'] . "</td>", 
     "<td>" . $threadDetailItem['threadCount'] . "</td>", 
     "<td>" . $threadDetailItem['lastUpdated'] . "</td>"); 
    echo $msg; 
} 

它打印出来(我创建了或上次更新字段):

2012-04-15 16点14分55秒

当我取代的sprintf线部分:

 "<td>" . $threadDetailItem['createdOn'] . "</td>", 

有:

 "<td>" . date("F j, Y, g:i a", $threadDetailItem['createdOn']) . "</td>", 

我得到

“1969年12月31日,7:33 PM” 在我phplog陈述遇到非合式数值的消息。我需要做什么才能正确显示正确的日期?我尝试将sprintf从%s更改为%d,但这不起作用。

在此先感谢您的建议。

+0

直接从MySQL中选择格式化的日期:http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format任何东西都不会浪费CPU时间做从string-> native-> string->等等的往返转换... – 2012-04-16 15:21:36

回答

5

这是因为$threadDetailItem['createdOn']是一个字符串,并且date()函数需要数字时间戳。使用strtotime() PHP函数将字符串转换为时间戳第一:

date("F j, Y, g:i a", strtotime($threadDetailItem['createdOn'])) 
+0

错字:stototime ... – 2012-04-16 15:20:46

+0

已经修复它:) – 2012-04-16 15:21:34

+0

非常感谢。就是这样,它是固定的。再次感谢 – jpporterVA 2012-04-16 15:23:48

-1

PHP的date()函数使用UNIX时间戳http://en.wikipedia.org/wiki/Unix_time,没有日期字符串。

我真的建议你改变你的数据库模式,改为使用BIGINT,并用日期(“U”)存储你的日期信息。如果你这样做,你会得到日期和区域设置格式的hazzel。 您也可以使用INT,但系统可以处理2038年之后的日期,如果这样做的话。

您可以使用strtotime()函数http://se2.php.net/manual/en/function.strtotime.php

date("F j, Y, g:i a", strtotime($threadDetailItem['createdOn'])) 

但是,如果您的日期存储在错误的语言环境,它会给你错误的答案。 当我说日期字符串和语言环境可能是一个真正的混乱时,请相信我。 这就是为什么你应该总是将日期存储在unixtimestamp中。

+1

不同意。你只需要确保你的设置正确。 – 2012-04-16 15:43:29

0

该字符串首先必须通过使用strtotime函数转换为时间戳。

$date=$variable['from-database']; 
date("Y-m-d",strtotime($date))