Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the simplest way to format a timestamp from SQL in PHP?

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;
like image 604
Josh Segall Avatar asked Oct 26 '08 14:10

Josh Segall


2 Answers

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;
like image 185
Aron Rotteveel Avatar answered Nov 09 '22 23:11

Aron Rotteveel


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');
like image 24
enobrev Avatar answered Nov 09 '22 23:11

enobrev