PHP:DateTime抛出具有合法时间戳的异常

时间:2012-08-21 18:37:09

标签: php datetime

我不明白:

$ts = strval( $this->get_start_date() ); // retrieve (int) timestamp from database

$time = new DateTime ( $ts ); 
    // throws an exception:  
    //'DateTime::__construct(): Failed to parse time string 
    //(1346284800) at position 7 (8): Unexpected character' 

$time = new DateTime();
$time->setTimestamp( $ts );
//works fine

知道这里发生了什么吗?我正在使用

PHP 5.3.10-1ubuntu3.2 with Suhosin-Patch (cli) (built: Jun 13 2012 17:19:58) 
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2012 Zend Technologies

2 个答案:

答案 0 :(得分:3)

要使用UNIX_TIMESTAMP初始化DateTime,请在开头使用 @

$time = new DateTime ('@'.$this->get_start_date()); 

请参阅PHP手册中的compound formats,了解strtodate()DateTime()接受的格式。

答案 1 :(得分:0)

检查DateTime::__construct()

DateTime的构造函数不等待unix timestamp,而是使用格式Y-m-d H:i:s

等待日期时间字符串

你的第二种方法很好。