Datetime PHP Formatting

You have a MySQL datetime column in your database and you want to display it in your PHP page. With this function, this becomes easily attainable. All that is required to pass in to the function is datetime variable you pulled down from the database and to assign a variable to the function. See this easy to follow example below.

The Code:

            <?php
            function ConvertDate($sql_date) {
            $date=strtotime($sql_date);
            $final_date=date("F j, Y, g:i a", $date);
            return $final_date;
            }
            ?>
            

Let me explain the function. First, I start off by declaring the function, naming it "ConvertDate". Also on this line I am "passing in" a variable, $sql_date. The variable $sql_date is the datetime cell from your MySQL database. On the second line, I use the strtotime PHP function to convert the datetime variable to a format PHP's date function can handle. Next line we specify how we want the date to read. In this example, the output would display something like "October 30, 2007, 9:34 am". If you want it to display something different, see PHP's date function page for formatting options. On the last line, I "return" $final_date, which is allows your function to store a variable for your convenience later.

After your function is setup, all you need to do is call your function on the page you want to display your datetime value on.

$date=ConvertDate($sql_date);
echo $date;

There may be other ways to accomplish this, but I've always used this method and it has always worked great for me.