user2370579
user2370579

Reputation: 361

Format Date while fetching the result of query

Ok, here is another one: I want to get the output from a mysql-query in a specific date format. Unfortunatley my code does not work. It must have something to do with "->format()", since without it I get the expected result. What am I doing wrong?

$sql = "
    SELECT 
        something,
        date
    FROM 
        table
    ";

$querynav = mysql_query($sql);

while($row = mysql_fetch_assoc($querynav)){

    $answer[] = array(
        'something' => $row['something'],
        'date' => (new DateTime($row['date']))->format('d.m.Y')
        );

}

Upvotes: 0

Views: 3944

Answers (3)

Amir
Amir

Reputation: 4111

'date' => ((new DateTime($row['date']))->format('d.m.Y'))

EDIT 1:

'date' => (new DateTime($row['date']))->format('d-m-Y')

Upvotes: -1

Vijaya Pandey
Vijaya Pandey

Reputation: 4282

If your $row['date'] have date, do this:

$newdate =  date('d.m.Y', strtotime($row['date']));

And you can the date in 12.03.2013 format.

EDIT:

while($row = mysql_fetch_assoc($querynav)){
    $newdate =  date('d.m.Y', strtotime($row['date']));

    $answer[] = array(
        'something' => $row['something'],
        'date' => $newdate 
        );

}

Upvotes: 2

Edwin Alex
Edwin Alex

Reputation: 5108

You can use Mysql DATE_FORMAT function.

SELECT something, DATE_FORMAT(date, '%m-%d-%Y') as date FROM table;

If you want to do in PHP, you can do like this.

$answer[] = array(
        'something' => $row['something'],
        'date'      => date('d-M-Y', strtotime($row['date']))
);

You don't have to use strtotime() function if your value is timestamp.

Upvotes: 3

Related Questions