Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

date_format() expects parameter 1 to be DateTime, string given

I'm trying to replace my queries to PDO query and I have problems with date formats. I need to print dates in format d/m/Y H:i:s but after PDO script runs it prints the date in this format Y-m-d H:i:s

    while($row = $sql -> fetch(PDO::FETCH_ASSOC))
  {
  ...
echo "<td>" . date_format( $row['date'], 'd/m/Y H:i:s'). "";"</td>";
  ...

  }
Warning: date_format() expects parameter 1 to be DateTime, string given in 

But if I change the code to echo "<td>" . $row['date']. "";"</td>"; then it returns to Y-m-d H:i:s How can I get the previous format d/m/Y H:i:s?

like image 786
Klapsius Avatar asked Aug 11 '14 07:08

Klapsius


2 Answers

The first parameter to date_format needs to be an object of DateTime class.

echo "<td>" . date_format( new DateTime($row['date']), 'd/m/Y H:i:s' ). "</td>";

or, alternatively

echo "<td>" . date_format( date_create($row['date']), 'd/m/Y H:i:s' ). "</td>";
like image 117
hjpotter92 Avatar answered Nov 14 '22 04:11

hjpotter92


Change your code to the following as provided in the PHP manual. As stated in the error you need to convert the value to DateTime object before outputting.

    while($row = $sql -> fetch(PDO::FETCH_ASSOC))
  {
$date = new DateTime($row['date']);
  ...
echo "<td>" . $date->format( $row['date'], 'd/m/Y H:i:s'). "";"</td>";
  ...

  }
like image 45
EternalHour Avatar answered Nov 14 '22 04:11

EternalHour