views:

437

answers:

5

I am retrieving date from MySQL in the format yyyy/mm/dd 00:00:00. I want to convert this date into format dd/MMM/yyyy in PHP. How to do this?

+6  A: 

Use PHP's date and strtotime:

$formatted = date('d/M/Y', strtotime($date_from_mysql));

Or use MySQL's built in DATE_FORMAT function:

SELECT DATE_FORMAT(datetime, '%d/%b/%Y') datetime FROM table

Or, you can mix a bit of both flavours:

SELECT UNIX_TIMESTAMP(datetime) timestamp FROM table;

$formatted = date('d/M/Y', $timestamp);

The last method is handy if you need to get several different formats on the same page; say, you would like to print the date and time separately, then you can just use date('d/M/Y', $timestamp) and date('H:i', $timestamp) without any further conversions.

Tatu Ulmanen
+5  A: 

Although you specifically asked for a php solution you might also be interested in MySQL's date_format() function.

SELECT date_format(dt, '%d/%m/%Y') ...
VolkerK
+1 For doing in the query what can be done.
jensgram
+1 MySQL internally stores the date as a number; this way, you parse and format the date only once.
Piskvor
But I am using Select * <table name>.
RPK
And you have to use `SELECT *` ? It would work with `SELECT *, DATE_FORMAT(...) as myDate FROM ...` but then MySQL would transmit the date field twice and the advantage that the date field had to be formatted only once is gone.
VolkerK
A: 

You should have a look at the date() function in PHP (docs).

print date('d/M/Y', $row['tstamp']);

This applies if your date field is a DATETIME or TIMESTAMP. Remeber to wrap the field in UNIX_TIMESTAMP() (docs), e.g. SELECT ..., UNIX_TIMESTAMP(dateField) AS tstamp FROM ....

jensgram
The seconds parameter for date() must be a unix timestamp, not the text representation of a MySQL DATETIME or TIMESTAMP. Therefore you'd have to use the UNIX_TIMESTAMP(date) function in your query, http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_unix-timestamp
VolkerK
You're right. Edited above. Thanks.
jensgram
A: 

You can actually get mySQL to convert the date to a unix timestamp

SELECT UNIX_TIMESTAMP(field) as date_field
FROM table

Then you can pass that straight into PHPs date() function to get the format you want

date('d/M/Y', $row['date_field'])
Neil Aitken
A: 
$d=date_create('2009-12-04 09:15:00');
echo $d->format('dd/M/yyyy');
dnagirl