Ayaz Alavi
Ayaz Alavi

Reputation: 4835

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

Upvotes: 5

Views: 3746

Answers (4)

amphetamachine
amphetamachine

Reputation: 30595

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

Upvotes: 2

Ayaz Alavi
Ayaz Alavi

Reputation: 4835

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

Upvotes: 1

cpf
cpf

Reputation: 1501

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

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

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

Upvotes: 11

Matti Virkkunen
Matti Virkkunen

Reputation: 65116

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?

Upvotes: 6

Related Questions