代码之家  ›  专栏  ›  技术社区  ›  Ayaz Alavi

DateTime对象有什么问题

  •  5
  • Ayaz Alavi  · 技术社区  · 16 年前

    谁能告诉我代码出了什么问题吗。

    $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()

    4 回复  |  直到 16 年前
        1
  •  11
  •   cpf    16 年前

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

    使$date变量为空,您只需调用它:

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

        2
  •  6
  •   Matti Virkkunen    16 年前

    如果您至少没有运行PHP5.3.0(如 the manual ,你一定在问之前读过,对吧?), setTimezone

        3
  •  2
  •   amphetamachine    16 年前

    manual , setTimeZone 将返回 DateTime FALSE 如果不能设置时区。保存返回实际上是不必要的,因为它将修改 日期时间

    也许你应该检查一下 setTimezone 在设置你的 $date 对象的返回值:

    $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
  •  1
  •   Ayaz Alavi    16 年前

    感谢每一位帮助过我的人,但只能标注正确答案。正确的代码是

    $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');
    
    推荐文章