What's wrong with a DateTime object

Can someone say 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: call to function member function () for non-object

+5
source share
4 answers

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

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

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

+11
source

If you are not using at least PHP 5.3.0 (as written in the manual that you probably read before the request, right?), It setTimezonewill return NULL instead of the modified DateTime. Do you use at least PHP 5.3.0?

+6
source

manual, setTimeZone DateTime, FALSE, " t . , DateTime, .

Perhaps you should check to see if setTimeZoneyour $datereturn value was set before setting your object :

$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');
+2
source

Thanks to everyone who helped, but only the correct answer can be noted. Correct code

$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');
+1
source

All Articles