Format a MySQL date in PHP
Dec 7th, 2008
I was looking through some very old code of mine and saw the hoops I jumped through to format a MySQL date field into something a little more friendly. It wasn't pretty, involving explode() among other things. Being more familiar with PHP now, I thought it would be nice to post a snippet of code. It takes a start date and an end date and returns just one date (in the format you specify per PHP date format, or a default one if you don't pass in the parameter) if the dates are the same, or the two dates with a dash in between if they are different. Nothing crazy here, and it could be improved by say adding an optional parameter to determine the separator when the dates don't match, or allowing the end date to be null, etc.. I think this will work in PHP4 too.
[php]
function mysqlDateFormat($startDate,$endDate,$format = 'M jS')
{
if($startDate == $endDate) {
return date($format,strtotime($startDate));
}
return date($format,strtotime($startDate)) . ' - ' . date($format,strtotime($startDate));;
}
[/php]
Posted In: Uncategorized, PHP