November 29, 2006

Working with dates in PHP and MySQL

You will find other articles relevant to this document in these sections:
Richard Lee @ 9:57 am

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)
Share and Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • digg
  • Furl
  • Reddit
  • YahooMyWeb

5 Comments »

  1. Nice Article, good reference snippets!

    Comment by Cameron Manderson — November 29, 2006 @ 10:33 am

  2. 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

  3. Good article. Nice function to know when you need to manipulate dates.

    Comment by Daniel Cedilotte — January 16, 2007 @ 3:43 am

  4. Thanks Dan

    Comment by Richard Lee — August 22, 2007 @ 12:11 pm

  5. Thanks. This was great.

    Comment by Tim — August 27, 2007 @ 2:11 am

RSS feed for comments on this post. TrackBack URI

Leave a comment