繁体   English   中英

使用 SQL 日期时间默认 current_timestamp 和格式

[英]Working with SQL datetime default current_timestamp and formatting

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

警告: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');
}

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

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

您需要做的是创建一个DateTime object 并在其上调用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');
}

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

改变

$date = $row["post_date"];

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM