September 6, 2006

Convert MySQL Date

Filed under: PHP, SQL — chris @ 7:02 pm

Let’s walk through the steps of creating a PHP function that will convert a MySQL date (2002-06-03) and turn that into a real world date. That way, if you ever use the date type of MySQL, you can use easily convert that date as you call it in your PHP code. It’s a small function that is driven almost solely by the substr function built into PHP.

First a quick note. It’s always a good idea to write a single file for a site called something like “db_connect.inc” and use that file by all of the other pages to connect to your Database. That way, it’s one change instead of a change on each page if you ever switch the database or the method of a connection. A great place to stick this function is in that file, since it probably won’t see much use outside of the times you make a connection. Just a thought.

Let’s start by defining the function name, along with creating the input and output strings.

function db_date($mysqlDate) {
$formatedDate = $mysqlDate;
return $formatedDate;
}

That’s the first step. Next, what do we want to use as the separator? A ‘-’, or a ‘/’ or something else? We should be able to set this when we call the function, so we’ll make it an optional attribute. That way, if we don’t set it when we call the function, it defaults to a ‘-’ (or anything else you want.)

function db_date($mysqlDate, $sep = '-') {

That’s it. Now when we want to add a ‘-’ to the output string, we just use the $sep variable instead. Next, we need to process that string with the substr function. The MySQL date is in a yyyy-mm-dd format. So we can just pick out the 3 sets of numbers then send those back out of the function (with the $sep separator we defined above.

$month = substr($mysqlDate,5,2);
$day = substr($mysqlDate,8,2);
$year = substr($mysqlDate,0,4);

The way substr works is by defining a string, defining a start position, then defining how many characters to read from the string starting from that start position. For month for example, we want to read the “$mysqlDate” string, starting at the point after the 5th character, and read the next two characters of that string.

Now that we have all 3 parts of the date, we combine them all and spit them out to the function. It ends up looking like this…

function db_date($mysqlDate, $sep = '-') {
$month = substr($mysqlDate,5,2);
$day = substr($mysqlDate,8,2);
$year = substr($mysqlDate,0,4);
$formatedDate = $month . $sep . $day . $sep . $year;
return $formatedDate;
}

… and we would call it from within the PHP page something like this…

echo(db_date($row['date']));

… assuming that the $row is the correct PHP variable in a MySQL loop of that PHP page. That’s it.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

You must be logged in to post a comment.