php date_format() 期望参数 1 是 DateTime,给定的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25237624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:44:45  来源:igfitidea点击:

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

phpdatedatetimedate-formatting

提问by Klapsius

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

我正在尝试将我的查询替换为 PDO 查询,但我在日期格式方面遇到了问题。我需要以 d/m/YH:i:s 格式打印日期,但在 PDO 脚本运行后,它会以这种格式打印日期 Ymd 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:sHow can I get the previous format d/m/Y H:i:s?

但是如果我将代码更改为echo "<td>" . $row['date']. "";"</td>";然后它返回到Y-m-d H:i:s如何获得以前的格式d/m/Y H:i:s

回答by hjpotter92

The first parameter to date_formatneeds to be an object of DateTimeclass.

第一个参数 todate_format需要是DateTime类的对象。

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

回答by EternalHour

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.

将您的代码更改为 PHP 手册中提供的以下内容。如错误中所述,您需要在输出之前将值转换为 DateTime 对象。

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

  }