类DateTime的对象无法转换为字符串

问题描述 投票:39回答:6

我有一个表格,其字符串值的格式为2012年4月20日星期五,名为Film_Release

我正在循环,我想在datetime中转换它们并将它们滚动到另一个表中。我的第二个表有一个名为Films_Date的列,格式为DATE。我收到此错误

类DateTime的对象无法转换为字符串

$dateFromDB = $info['Film_Release'];
 $newDate = DateTime::createFromFormat("l dS F Y",$dateFromDB); //( http:php.net/manual/en/datetime.createfromformat.php)

然后我通过insert命令将$ newdate插入表中。

为什么我会收到这样的错误?

php mysql datetime insert
6个回答
62
投票

因为$newDateDateTime类型的对象,而不是字符串。 documentation是明确的:

返回根据指定格式格式化的新DateTime对象。

如果你想从字符串转换为DateTime回到字符串以更改格式,请在末尾调用DateTime::format以从DateTime中获取格式化的字符串。

$newDate = DateTime::createFromFormat("l dS F Y", $dateFromDB);
$newDate = $newDate->format('d/m/Y'); // for example

13
投票

试试这个:

$Date = $row['valdate']->format('d/m/Y'); // the result will 01/12/2015

注意:$row['valdate']是数据库中的值日期


3
投票

使用此:$newDate = $dateInDB->format('Y-m-d');


0
投票

你试图将$newdate插入你的数据库。您需要先将其转换为字符串。使用DateTime::format方法转换回字符串。


0
投票

检查以确保有电影上映日期;如果缺少日期,则无法在非对象上进行格式化。

if ($info['Film_Release']){ //check if the date exists
   $dateFromDB = $info['Film_Release'];
   $newDate = DateTime::createFromFormat("l dS F Y", $dateFromDB);
   $newDate = $newDate->format('d/m/Y'); 
} else {
   $newDate = "none"; 
}

要么

 $newDate = ($info['Film_Release']) ? DateTime::createFromFormat("l dS F Y", $info['Film_Release'])->format('d/m/Y'): "none" 

0
投票

这是一种offtopic,但我来自谷歌搜索相同的错误。对我来说,当我从mssql数据库中选择datetime字段而不是稍后在php-script中使用它时,会出现此错误。像这样:

$SQL="SELECT Created
FROM test_table";

$stmt = sqlsrv_query($con, $SQL);
if( $stmt === false ) {
    die( print_r( sqlsrv_errors(), true));
}

$Row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC);


$SQL="INSERT INTO another_test_table (datetime_field) VALUES ('".$Row['Created']."')";
$stmt = sqlsrv_query($con, $SQL);
if( $stmt === false ) {
    die( print_r( sqlsrv_errors(), true));
}

INSERT语句给出了错误:Object of class DateTime could not be converted to string

我意识到你不能只从数据库中选择日期时间:

SELECT Created FROM test_table

但是你必须在这个领域使用CONVERT:

SELECT CONVERT(varchar(24),Created) as Created FROM test_table
© www.soinside.com 2019 - 2024. All rights reserved.