I have a query that returns a date, and I’d like to format it before I display it to users on my page. However, when I use format, the date appears to be null (displays year 1969). Here is the code that gets the data:
$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();
When I print it out with the following code (in a different function):
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;
}
It prints out (for my created On or last Updated fields):
2012-04-15 16:14:55
When I replaced the portion of the sprintf line:
"<td>" . $threadDetailItem['createdOn'] . "</td>",
with:
"<td>" . date("F j, Y, g:i a", $threadDetailItem['createdOn']) . "</td>",
I get
“December 31, 1969, 7:33 pm” and a message in my phplog stating a non-well formed numeric value encountered. What do I need to do get the the right date displayed correctly? I’ve tried changing the sprintf from %s to %d, but that doesn’t work.
Thanks in advance for your suggestions.
It’s because
$threadDetailItem['createdOn']is a string, and thedate()function expects a numeric timestamp. Use thestrtotime()PHP function to convert the string to a timestamp first: