Working with dates in PHP and MySQL
Here’s some quick examples of a few different ways you can work with date/ or datetime fields rom a MySQL database. Hope you find them helpful ![]()
Formatting date with MySQL for output:
$query = mysql_query("SELECT DATE_FORMAT(event_date, '%d/%m/%y') AS formatted_date FROM events");
$row = mysql_fetch_array($query);
echo $row['formatted_date'];
// output: 20/11/06
Retrieving a date from MySQL with the intention of using it for calculation (timestamp conversion):
$query = mysql_query("SELECT UNIX_TIMESTAMP(event_date) AS timestamp FROM events");
$timestamp = mysql_fetch_array($query);
echo $row['timestamp'];
// output: 20061120091528 i.e. 2006-11-20 09:15:28
Formatting a date string with PHP for output:
$query = mysql_query("SELECT event_date FROM events");
$row = mysql_fetch_array($query);
$formatted_date = date('d m y', strtotime($row['event_date']));
echo $formatted_date;
// output: 20/11/06
Converting formatted date strting for calculation in PHP (timestamp conversion):
$query = mysql_query("SELECT DATE_FORMAT(event_date, '%d/%m/%y') AS formatted_date FROM events");
$row = mysql_fetch_array($query);
echo 'Formatted date: '.$row['formatted_date'];
//output : 20/11/06
$timestamp = strtotime($row['formatted_date']));
echo 'Timestamp '.$timestamp;
// output: 20061120091528 (i.e. 2006-11-20 09:15:28)






Nice Article, good reference snippets!
Comment by Cameron Manderson — November 29, 2006 @ 10:33 am
Thanks man
. I’ve always found dealing with dates is tedious! Do you have any good examples of setting timezones cam?
Comment by Richard Lee — November 29, 2006 @ 12:10 pm
Good article. Nice function to know when you need to manipulate dates.
Comment by Daniel Cedilotte — January 16, 2007 @ 3:43 am
Thanks Dan
Comment by Richard Lee — August 22, 2007 @ 12:11 pm
Thanks. This was great.
Comment by Tim — August 27, 2007 @ 2:11 am