Home > Mobile >  Adding 30 days to DateTime with TimeZone is resulting to an error: "Call to a member function m
Adding 30 days to DateTime with TimeZone is resulting to an error: "Call to a member function m

Time:09-08

I am trying to add 30 days to the current day using the php modify() function and I also am putting timezone in the datetime here is my code:

$country_code = 'PH';
$timezone = \DateTimeZone::listIdentifiers(\DateTimeZone::PER_COUNTRY, $country_code);
$new_date = (new \DateTime("now", new \DateTimeZone($timezone[0])))->format('Y-m-d H:i:s');
$datetime = $new_date->modify(' 30 days');  
$end_date = $datetime->format('Y-m-d H:i:s');

I am getting the error:

Call to a member function modify() on string

When I echo the $new_date it is in proper MySQL datetime format 'Y-m-d H:i:s'. What am I doing wrong?

CodePudding user response:

Remove the ->format('Y-m-d H:i:s') as that creates $new_date as a string and not a DateTime Object that has a modify() method on it

$country_code = 'PH';
$timezone = \DateTimeZone::listIdentifiers(\DateTimeZone::PER_COUNTRY, $country_code);
$new_date = (new \DateTime("now", new \DateTimeZone($timezone[0])));
$new_date->modify(' 30 days');  
$end_date = $new_date->format('Y-m-d H:i:s');

Or you could do it all in one line

$new_date = (new \DateTime("now", new \DateTimeZone($timezone[0])))->modify(' 30 days')->format('Y-m-d H:i:s');

CodePudding user response:

ok this is crazy, I played with it and came up with a 1 liner solution..

$end_date = (new \DateTime("now", new \DateTimeZone($timezone[0])))->modify(' 30 days')->format('Y-m-d H:i:s');

Apparently it should be formatted after being modified but in my earlier code it is being formatted first before modified then formatted once again.

  • Related