2012-04-18 147 views
29

我有一個字符串值的表中週五20日2012年4月在一個名爲Film_Release對象無法轉換爲字符串

我循環通過實地的格式,我想將它們轉換中日期時間並將它們推出到另一個表中。我的第二個表有一個名爲Films_Date的列,格式爲DATE。我收到此錯誤類,日期時間的

對象無法轉換爲字符串

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

然後,我通過一個插入命令插入newdate $到表中。

爲什麼我會得到這樣的錯誤?

回答

52

因爲$newDateDateTime類型的對象,而不是字符串。該documentation是明確的:

Returns new DateTime object formatted according to the specified format.

如果你想從一個字符串轉換爲DateTime返回字符串轉換格式,呼籲DateTime::format末得到一個格式化字符串出你DateTime的。

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

嗨,ive試過了,我得到這個錯誤 - 調用一個非對象的成員函數格式() – DIM3NSION 2012-04-18 13:21:54

+0

@ DIM3NSION:不可能與上面的代碼,除非'createFromFormat'不返回一個對象,這意味着它返回'false',因爲輸入無效。閱讀[文檔](http://www.php.net/manual/en/datetime.createfromformat.php)並修復輸入。 – Jon 2012-04-18 14:05:41

+0

我將使用什麼類型的字段來插入$新日期?我現在工作 – DIM3NSION 2012-04-18 15:03:37

0

您正試圖將$newdate插入到您的db中。您需要先將其轉換爲字符串。使用DateTime::format方法轉換回字符串。

+0

嗨,我試圖使用格式,但收到一個錯誤 - 調用一個非對象的成員函數格式() – DIM3NSION 2012-04-18 13:40:41

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

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

10

試試這個:

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

注:$row['valdate']其值日期在數據庫

+1

它解決了這個問題:) – DiChrist 2016-11-15 16:42:28

0

這是一種不合時宜的方式,但是我通過使用Google搜索同樣的錯誤來到這裏。 對我來說,這個錯誤出現在我從mssql數據庫中選擇日期時間字段並且稍後在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

我意識到你CAN NOT只需從數據庫中的日期時間:

SELECT Created FROM test_table 

你必須使用CONVERT這個字段:

SELECT CONVERT(varchar(24),Created) as Created FROM test_table 
+0

使用params肯尼,他們在那裏爲它會奇蹟般地從\ DateTime對象sqlsrv_query($ con,「INSERT INTO tablename(dtfield)VALUES(?)」,array($ datetime))轉換成''' – GDmac 2018-01-16 10:36:38