在非对象DateTime上调用成员函数format()


Call to a member function format() on a non-object 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异常。

您应该使用("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

检查此示例

您没有创建任何类的对象,因此如果出现错误,您需要创建类对象或直接使用。

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

或者您需要通过correct format in Datetime(),请参阅@此的Alpha答案

更多阅读手册:-http://php.net/manual/en/datetime.createfromformat.php

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

然后您可以使用$date->format('Y')来获取年份。。。