2014-10-07 22 views
1

此問題可能很常見,但似乎無法找出我做錯了什麼。調用非對象的成員函數格式()DateTime

我有兩個變量的日期和時間從數據庫,我認爲是UTC格式,我需要轉換爲AEST;

$date = message['date']; //25/09/2014 
$time = message['time']; //9:00:00 

$combined_time = $date . " " . $time; 
$schedule_date = DateTime::createFromFormat("Y-m-d H:i:s",$combined_time ,new DateTimeZone("Australia/Melbourne")); 
return $schedule_date->format("jS-A-Y H:i:s T"); 

我得到了Call to a member function format() on a non-object異常。

回答

3

您應該使用("d/m/Y h:i:s"):

$schedule_date = DateTime::createFromFormat("d/m/Y h:i:s", $combined_time , new DateTimeZone("Australia/Melbourne")); 

給定的格式是錯誤的,因爲你的日期時間爲25/09/2014 9:00:00檢查this example

+1

示例鏈接不起作用。 – Star 2018-02-12 07:27:01

+0

謝謝@Star,刪除它:-) – 2018-02-12 10:10:40

2

您不會創建任何類的對象,因此您需要創建類對象或直接使用該對象。

$schedule_date = new DateTime($date); 
return $schedule_date->format("jS-A-Y H:i:s T"); 

,或者你需要傳遞correct format in Datetime()看到@The阿爾法回答這個

詳細閱讀說明書: - http://php.net/manual/en/datetime.createfromformat.php

+0

謝謝,我剛拿到現在。我想我只是在'DateTime :: createFromFormat(「Y-m-d H:i:s」)中做了錯誤的格式。 – blitzen12 2014-10-07 05:09:59

+0

'DateTime :: createFromFormat'工作,不需要使用'新日期時間'[ – 2014-10-07 05:12:59

+0

] [檢查此工作示例](http://codepad.viper-7.com/YiIRo6)。 DateTime :: createFromFormat返回一個DateTime對象。 – 2014-10-07 05:16:31

0
// convert string to timestamp 
    $timeStamp = strtotime($combined_time); 
    // create DateTime object use timestamp 
    $date = new DateTime(); 
    $date->setTimestamp($timeStamp); 

然後你可以使用$日期 - >格式( 'Y')來獲得一年...

相關問題