从 Mysqli 返回的 PHP 格式日期


format date in php returned from mysqli

我有一个返回日期的查询,我想在页面上向用户显示它之前设置它的格式。 但是,当我使用格式时,日期显示为空(显示年份 1969)。 下面是获取数据的代码:

$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",我的 phplog 中有一条消息,指出遇到了格式不正确的数值。 我需要做什么才能正确显示正确的日期? 我尝试将冲刺从 %s 更改为 %d,但这不起作用。

提前感谢您的建议。

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

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

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

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

Php 的 date() 函数使用 unix 时间戳 http://en.wikipedia.org/wiki/Unix_time,而不是日期字符串。

我真的建议您更改数据库模式以使用 BIGINT,并使用 date("U") 存储您的日期信息。如果你这样做,你将绕过日期和区域设置格式的麻烦。您也可以使用 INT,但如果这样做,系统可以处理 2038 年之后的日期。

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

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

但是,如果您的日期存储在错误的区域设置中,它将给您错误的答案。当我说日期字符串和区域设置可能一团糟时,请相信我。这就是为什么您应该始终将日期存储在 unixtimestamp 中的原因。