What is the simplest, fastest way to complete the PHP code below such that the output is in a user-friendly format (for example, "October 27, 2006")?
$result = mysql_query("SELECT my_timestamp FROM some_table WHERE id=42", $DB_CONN);
$row = mysql_fetch_array($result);
$formatted_date = ???($row['my_timestamp']);
echo $formatted_date;
You could use MySQL to do this for you,
$result = mysql_query("SELECT DATE_FORMAT(my_timestamp, '%M %d, %Y) AS my_timestamp FROM some_table WHERE id=42", $DB_CONN);
$row = mysql_fetch_array($result);
$formatted_date = $row['my_timestamp'];
echo $formatted_date;
Or use PHP,
$result = mysql_query("SELECT my_timestamp FROM some_table WHERE id=42", $DB_CONN);
$row = mysql_fetch_array($result);
$formatted_date = strftime('%B %d, %y', $row['my_timestamp']);
echo $formatted_date;
I tend to do the date formatting in SQL, like Aron's answer. Although for PHP dates, I prefer using the DateTime object (PHP5+) over date:
$timestamp = new DateTime($row['my_timestamp']);
echo $timestamp->format('F j, Y') . '<br />';
echo $timestamp->format('F j, Y g:ia');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With