How To Format a MySQL Date For Output in PHP

By | September 15, 2009

The following PHP code parses the date portion out of a MySQL date column and lets you format it according to the formatting rules of the PHP date function.

// Parse date portion of a date field and format it according to the date() function.
// Second parm is optional. 
function FmtDateTime($dt, $fmt = "F d, Y")
{
	$arr = explode("-", substr($dt, 0, 10)); 
	//	$fmt of "m/d/Y" prints date in mm/dd/yyyy format. 
	//  $fmt of "F d, Y" prints date in Spelled out month day, YYYY format
	
	echo date($fmt, mktime(0,0,0, $arr[1], $arr[2], $arr[0])); 
}

To use it, you can do something like this:

<?php
   FmtDateTime($scdDate, "l d F, Y" ); ?> 

(This prints 2009-09-15 as “Tuesday 15 September, 2009”).

If you omit the second parameter on the function call, the date will print like this:
“September 15, 2009”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.