tags:

views:

93

answers:

4

Hi, 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

+3  A: 

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?

Matti Virkkunen
it gotto be less than 5.3 because removing assigment solved the issue
Ayaz Alavi
You can get your version by typing `php -v` from the command line.
Erik
+6  A: 

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

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

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

cpf
+2  A: 

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');
amphetamachine
A: 

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');
Ayaz Alavi