【问题标题】:Working with SQL datetime default current_timestamp and formatting使用 SQL datetime 默认 current_timestamp 和格式化
【发布时间】:2019-10-26 22:53:47
【问题描述】:

我在 MySQL 数据库中有一个列,它是 DATETIME 数据类型,其默认值为 CURRENT_TIMESTAMP。我正在尝试使用 PHP 的 date_format() 函数对其进行格式化,这给了我以下错误

警告:date_format() 期望参数 1 为 DateTimeInterface, C:\wamp64\www\cms\CMS_TEMPLATE\includes\content.php 中给出的字符串 第 26 行

$stmt = $connect->link->query("SELECT post_date FROM posts");
while($row = $stmt->fetch()){
    $date = $row["post_date"];
    echo date_format($date,'d/F/Y g:i A');
}

我应该使用不同的函数还是只是语法错误?

【问题讨论】:

    标签: php date datetime


    【解决方案1】:

    您正在使用一个不应单独使用的功能。最好将程序样式函数抛在后面,因为它们通常会导致混淆和错误,就像您的示例中的情况一样。

    您需要做的是创建一个DateTime 对象并在其上调用format 方法。可以使用优先括号在一行中完成。

    $stmt = $connect->link->query("SELECT post_date FROM posts");
    while ($row = $stmt->fetch()) {
        echo (new DateTime($row["post_date"]))->format('d/F/Y g:i A');
    }
    

    附带说明,foreach 循环通常看起来比while 循环更干净。

    $stmt = $connect->link->query("SELECT post_date FROM posts");
    foreach ($stmt as $row) {
        echo (new DateTime($row["post_date"]))->format('d/F/Y g:i A');
    }
    

    【讨论】:

      【解决方案2】:

      警告指出您应该将DateTimedate_format() 一起使用(“DateTime 实现 DateTimeInterface”)

      改变

      $date = $row["post_date"];
      

      $date = new DateTime($row["post_date"]);
      

      【讨论】:

        猜你喜欢
        • 2013-05-16
        • 2017-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多