Search code examples
phpmysqldatedate-conversion

PHP how to convert date from mysql?


I am using MySQL and php. When I get a date from MySQL it is in the format yyyy-MM-dd. Once I get this string, how can I convert it to format of example Jan 2 2013 in php?

I tried

date("M j Y", mysql_result($recordset, $i, 'date_started'));

using http://www.php.net/manual/en/function.date.php as a reference, but I get some weird date as the output.


Solution

  • The PHP date() method needs a timestamp, so convert your mysql date string to a timestamp first using strtotime():

    date("M j Y", strtotime(mysql_result($recordset, $i, 'date_started')));
    

    Or better yet, format your date in your mysql query directly using DATE_FORMAT. You don't really even need PHP to do this.