为带时区的DateTime添加30天报错:Call to a member function modify() on string
问题:PHP调用modify()函数时出现"Call to a member function modify() on string"错误
我尝试使用PHP的modify()函数为当前日期添加30天,同时为DateTime设置时区,代码如下:
$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');
运行时出现错误:
Call to a member function modify() on string
输出$new_date为标准MySQL datetime格式'Y-m-d H:i:s',请问我哪里操作错误?
解答
错误原因很直接:你调用format()方法后,$new_date已经变成了字符串类型,而modify()是DateTime对象的成员方法,字符串无法调用这个方法。
正确的做法是先保留DateTime对象,完成日期修改操作后,再调用format()转成需要的字符串格式。
修改后的代码示例1:
$country_code = 'PH'; $timezone = \DateTimeZone::listIdentifiers(\DateTimeZone::PER_COUNTRY, $country_code); // 先创建DateTime实例,不立即转换为字符串 $datetime = new \DateTime("now", new \DateTimeZone($timezone[0])); // 调用modify修改日期 $datetime->modify('+30 days'); // 最后转换为目标格式 $end_date = $datetime->format('Y-m-d H:i:s');
或者用链式调用简化代码:
$country_code = 'PH'; $timezone = \DateTimeZone::listIdentifiers(\DateTimeZone::PER_COUNTRY, $country_code); $end_date = (new \DateTime("now", new \DateTimeZone($timezone[0]))) ->modify('+30 days') ->format('Y-m-d H:i:s');
核心要点:format()方法的返回值是字符串,只有DateTime对象才能调用modify()、add()这类日期修改方法,所以要避免提前把对象转成字符串。
内容的提问来源于stack exchange,提问作者Emack2
相关产品推荐
相关产品推荐

