我在周五20日2012年4月的格式字符串值的表在一个名为Film_Release场
我通过循环,我想将它们转换的日期时间和转出来到另一个表。 我的第二个表有一个称为Films_Date柱,带日期的格式。 我收到此错误
一流的DateTime的对象无法转换为字符串
$dateFromDB = $info['Film_Release'];
$newDate = DateTime::createFromFormat("l dS F Y",$dateFromDB); //( http:php.net/manual/en/datetime.createfromformat.php)
然后,我通过一个插入命令插入newdate $到表中。
为什么我会得到这样的错误?
因为$newDate
是类型的对象DateTime
,而不是一个字符串。 该文件是明确的:
返回新DateTime
按照指定的格式进行格式化的对象。
如果你想从一个字符串转换DateTime
回字符串转换格式,调用DateTime::format
在最后得到一个格式化字符串出你的DateTime
。
$newDate = DateTime::createFromFormat("l dS F Y", $dateFromDB);
$newDate = $newDate->format('d/m/Y'); // for example
试试这个:
$Date = $row['valdate']->format('d/m/Y'); // the result will 01/12/2015
注: $row['valdate']
它在数据库中的值日期
使用此: $newDate = $dateInDB->format('Ym-d');
你试图插入$newdate
到您的分贝。 您需要先将其转换为字符串。 使用DateTime::format
的方法来转换回一个字符串。
检查以确保有一个电影的上映日期; 如果日期是缺失的,你就不能到非对象上进行格式化。
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"
这是一种offtopic,但我来到这里,从谷歌上搜索同样的错误。 对我来说,当我从MSSQL数据库,比PHP脚本后使用它选择日期时间字段出现此错误。 像这样:
$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