致命错误:调用未定义的方法DateTime :: setTimestamp()

时间:2013-05-15 00:05:31

标签: php

仅在一台特定服务器上获取上述错误 - 但不是其他服务器。假设这是一个php版本问题。 以下是触发错误的代码:

//get time interval
    static function get_interval($now, $post_time){
        $datetime1 = new DateTime();
        $datetime1->setTimestamp($now);

最后一行导致了问题。关于如何绕过它的任何想法?

1 个答案:

答案 0 :(得分:8)

如果您的PHP版本低于5.3,那么您可以使用此类来使用“setTimestamp”和“getTimestamp”函数:

<?php

class MyDateTime extends DateTime
{
    public function setTimestamp( $timestamp )
    {
        $date = getdate( ( int ) $timestamp );
        $this->setDate( $date['year'] , $date['mon'] , $date['mday'] );
        $this->setTime( $date['hours'] , $date['minutes'] , $date['seconds'] );
    }

    public function getTimestamp()
    {
        return $this->format( 'U' );
    }
}

$date = new MyDateTime();
$date->setTimestamp( $someTimestamp );

echo $date->format( 'd/m/Y H:i:s' );

?>