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

不羁的心 提交于 2019-12-19 06:59:11

问题


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?


回答1:


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>";



回答2:


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>";
  ...

  }


来源:https://stackoverflow.com/questions/25237624/date-format-expects-parameter-1-to-be-datetime-string-given

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!