【问题标题】:Whats wrong with DateTime objectDateTime 对象有什么问题
【发布时间】:2010-05-31 12:43:32
【问题描述】:

谁能告诉我代码有什么问题。

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

错误是:在非对象上调用成员函数 format()

【问题讨论】:

    标签: php datetime date


    【解决方案1】:

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

    使 $date 变量为空,你应该调用它:

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

    【讨论】:

    • 哇哦,它也解决了我的问题。非常感谢你
    【解决方案2】:

    如果您至少没有运行 PHP 5.3.0(如the manual 中所写,您一定会在询问之前阅读,对吗?),setTimezone 将返回 NULL 而不是修改后的 DateTime。您是否至少运行 PHP 5.3.0?

    【讨论】:

    • 它必须小于 5.3,因为删除分配解决了问题
    • 您可以通过在命令行中输入php -v 来获取您的版本。
    【解决方案3】:

    根据manualsetTimeZone 将返回DateTime 对象或FALSE,如果它不能设置时区。保存返回实际上是不必要的,因为它会修改你传递给它的DateTime 对象。

    也许您应该在将$date 对象设置为其返回值之前检查setTimezone 是否成功:

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

    【讨论】:

      【解决方案4】:

      感谢所有帮助但只能标记为正确答案的人。正确的代码是

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-01
        • 1970-01-01
        • 2022-11-02
        • 2011-10-31
        • 2016-05-11
        • 2014-06-26
        • 2013-02-19
        相关资源
        最近更新 更多