开发者

Whats wrong with DateTime object

开发者_运维技巧Can anyone tell what is wrong with the code.

$timezone = "Asia/Karachi"; 
$date = new DateTime($when_to_send, new DateTimeZone($timezone));
$date = $date->setTimezone(new DateTimeZone('GMT')); 
$when_to_send = $date->format('Y-m-d H:i:s');

error is: Call to a member function format() on a non-object


$date = $date->setTimezone(new DateTimeZone('GMT'));

Makes the $date variable null, you should just call it:

$date->setTimezone(new DateTimeZone('GMT'));


If you're not running at least PHP 5.3.0 (as written in the manual, which you surely read before asking, right?), setTimezone will return NULL instead of the modified DateTime. Are you running at least PHP 5.3.0?


According to the manual, setTimeZone will return either a DateTime object or a FALSE if it can't set the timezone. Saving the return is actually unnecessary because it will modify the DateTime object you pass it.

Perhaps you should check whether setTimezone succeeded before setting your $date object to its return value:

$timezone = "Asia/Karachi";
$date = new DateTime($when_to_send, new DateTimeZone($timezone));

if (! ($date && $date->setTimezone(new DateTimeZone('GMT'))) ) {
    # unable to adjust from local timezone to GMT!
    # (display a warning)
}

$when_to_send = $date->format('Y-m-d H:i:s');


Thanks for everyone who helped but only can be marked correct answer. Correct code is

$timezone = "Asia/Karachi"; 
$date = new DateTime($when_to_send, new DateTimeZone($timezone));
$date->setTimezone(new DateTimeZone('GMT')); 
$when_to_send = $date->format('Y-m-d H:i:s');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜