Here’s a useful function that I use a lot for taking a database date and converting it into something human readable.

  1. function dateFormat($dbDate, $newFormat="jS F Y") {
  2.  
  3.         // split the date into it’s component parts
  4.         $year=substr($dbDate, 0,4);
  5.         $month=substr($dbDate, 5,2);
  6.         $day=substr($dbDate, 8,2);
  7.         $hour=substr($dbDate, 11,2);
  8.         $minute=substr($dbDate, 14,2);
  9.         $second=substr($dbDate, 17,2);
  10.  
  11.         // recompile in the required format
  12.         return date($newFormat, mktime($hour,$minute,$second,$month,$day,$year));
  13.  
  14. }

Uses

The function can be used in the following way.

  1. echo dateFormat("2010-11-01 18:00:00", "l jS")

returns

Monday 1st
  1. echo dateFormat("2010-11-01 18:00:00")

returns

1st November 2010

Breakdown

Now I’ll break the code down

  1. function dateFormat($dbDate, $newFormat="jS F Y") {

This line sets the function name dateFormat. It also sets the parameters used throughout the function $dbDate and $newFormat also included is a default parameter for $newFormat. This is used if you do not pass a parameter when calling the function.

  1. // split the date into it’s component parts
  2. $year=substr($dbDate, 0,4);
  3. $month=substr($dbDate, 5,2);
  4. $day=substr($dbDate, 8,2);
  5. $hour=substr($dbDate, 11,2);
  6. $minute=substr($dbDate, 14,2);
  7. $second=substr($dbDate, 17,2);

This splits the passed date into it’s component parts so that it can be reformed into the desired format.

  1. // recompile in the required format
  2. return date($newFormat, mktime($hour,$minute,$second,$month,$day,$year));

The final line of the function uses the mktime and date function to reprocess your date into the $newFormat supplied.

I hope you find this function useful, I use it for many sites with great success.