Namit
Namit

Reputation: 1322

Change date format in php retrieved from mysql

I have a column in mysql which stores the dates. So in mysql the dates are stored in Y-M-D format. However on retrieval i want to view change that format to D-M-Y . I read online at a few places and i found the date() in php, Date conversion. But they are generally for timestamp, also in many cases people had recommended to split the variable by - and then changing position.

My question is that, is splitting the variable the only option here or do we have any built in function that does that for us?

Upvotes: 3

Views: 23786

Answers (3)

Saket Patel
Saket Patel

Reputation: 6683

this should work for you, check here http://codepad.org/YdZQzgXR

<?
   $date = '2012-12-30';
   echo date('d-m-Y', strtotime($date));
?>

Upvotes: 15

KARASZI Istv&#225;n
KARASZI Istv&#225;n

Reputation: 31467

You can do that on the PHP side or on the MySQL side.

On the MySQL side you could use DATE_FORMAT:

SELECT DATE_FORMAT(NOW(), '%d-%m-%Y');

or from a field:

SELECT id, DATE_FORMAT(created_at, '%d-%m-%Y') FROM articles;

On the PHP side you have more tools:

  • use a database abstraction layer (PDO, MDB, etc.)
  • parse the returned time with strptime and then use strftime to format it
  • split as you mentioned
  • ...

Upvotes: 7

Niko
Niko

Reputation: 26730

Two possibilities: PHP's strtotime() or let MySQL do the job!

Upvotes: 2

Related Questions