0

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.

Jason
  • 15,017
  • 23
  • 85
  • 116
omega
  • 40,311
  • 81
  • 251
  • 474

3 Answers3

2

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.

jszobody
  • 28,495
  • 6
  • 61
  • 72
  • Has no one heard of DateTime? – Rottingham Jan 03 '14 at 01:24
  • @Rottingham sure, but strtotime() is just simpler in this particular case. especially since you can keep it inline, and not need to break up the code if you don't want to. – jszobody Jan 03 '14 at 01:26
  • True, I still tend to lean on DateTime because once I have the object, I can do much more with it in a 'pretty fashion', like $date->sub(new DateInterval('P1D')); – Rottingham Jan 03 '14 at 01:28
  • @Rottingham certainly, and I push DateTime also as good OO development in general. just trying to answer the specific question here with the simplest answer. – jszobody Jan 03 '14 at 01:29
  • Not criticizing you Js, good answer! :-) – Rottingham Jan 03 '14 at 01:29
  • There is a min wait time before you can mark the answer as correct. – omega Jan 03 '14 at 01:33
2

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');
Rottingham
  • 2,593
  • 1
  • 12
  • 14
1

you could use date_format in mysql like this

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

Charles0429
  • 1,406
  • 5
  • 15
  • 31