Pregunta

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.

¿Fue útil?

Solución

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.

Otros consejos

Using the DateTime wrapper gives you functionality that is worth having. To convert from mysql Format, simple follow this pattern.

$mysqlDate = '2014-01-01';
$myDate = new DateTime($mysqlDate);

echo $myDate->format('M j Y');

you could use date_format in mysql like this

DATE_FORMAT(NOW(),'%b %d %y') //%b is the short name of a month

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top