Nick Galgay
Nick Galgay

Reputation: 57

Formatting MySQL date in foreach

I'm a noob to MySQL and have a question. How would I format the date taken from a column?

My code is $row = $wpdb->get_results("select * from wp_miles");

foreach ( $row as $row ) { echo "$row->mile_history on $row->date<BR>";}

it's obviously the $row->date I want to change from 2016-02-13 to M j. Thanks

Upvotes: 1

Views: 220

Answers (4)

Nick Galgay
Nick Galgay

Reputation: 57

Here's what worked.

foreach ( $row as $row ) { echo "$row->mile_history on" . "&nbsp;" . date("M j",strtotime($row->date)) . "<BR>";}

I used Matts answer and had to change small things. Thanks Matt and everyone else for the help.

:)

Upvotes: 0

smozgur
smozgur

Reputation: 1812

You can also do that directly in your MySQL query. Whether replacing the same field value or using another field name like "formattedDate".

"select *, date_format(date, '%b %e') AS date from wp_miles"

or as new field if you also need date field as date value in php but I don't prefer this method if you also need to use date as date value in php since it will return more data from the query.

"select *, date_format(date, '%b %e') AS formattedDate from wp_miles"

Upvotes: 2

trank
trank

Reputation: 1012

you can use mysql DATE_FORMAT function in your query string: SELECT DATE_FORMAT(date, '%M %j') as date, ... FROM ...

Upvotes: 0

Niklesh Raut
Niklesh Raut

Reputation: 34914

Use this

  date("M j",strtotime($row->date));

Upvotes: 2

Related Questions