Formatting Dates

I have a field named Born, in the date format. After my query, I display a value from the field…

 $Born = $row['Born'];
 echo $Born;

It displays 1955-01-07, which is exactly what’s in the database. However, I want to format it to display Jan. 7, 1955. So I checked the PHP Manual, and it looks like I’m supposed to do something like this…

 $Born = $row['Born'];
 $Born = date("F j, Y");
 echo $Born;

However, my solution displays August 11, 2013, which isn’t even in my database.

Can anyone tell me what I’m doing wrong? Thanks.

Hi Chavista,

The date function returns the current system date in the format you specify, unless you provide a timestamp as the second argument.

You can use PHP’s DateTime class to get the result you want:

$Born = new DateTime($row['Born']);
echo $Born->format("M. j, Y");

When you use the date() function, the current date & time are automatically supplied if you don’t specify a specific date/time.

However, using the date() function based on the UNIX timestamp is a little out of date now. It’s better to use the DateTime class.

$Born = $row['Born'];
$BornDate = DateTime::createFromFormat('Y-m-d', $Born);
echo $BornDate->format('M j, Y');

Or, if you prefer the procedural code style instead of the object-oriented code style:

$Born = $row['Born'];
$BornDate= date_create_from_format('Y-m-d', $Born);
echo date_format($BornDate, 'M j, Y');

That works great; thanks. :wink: