0

我有这个$date数组:

Array
(
[start] => DateTime Object
    (
        [date] => 2013-09-19 00:00:00
        [timezone_type] => 3
        [timezone] => Europe/London
    )

[end] => DateTime Object
    (
        [date] => 2013-10-20 23:59:00
        [timezone_type] => 3
        [timezone] => Europe/London
    )

)

我想以时间戳格式回显开始日期值(2013-09-19 00:00:00)我试过echo $date['start']->date->getTimestamp();但它返回了这个错误: Fatal error: Call to a member function getTimestamp() on a non-object in ...

4

1 回答 1

3

您正在寻找:

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

我相信...在手册页上检查所有可能的格式
不要让转储欺骗您,该DateTime对象没有公共date属性,正如您在此处看到的那样。但是,它确实有一个方法,该方法返回一个 int ,getTimestamp就像参考手册一样。 您可以使用任何预定义的常量(所有字符串,代表标准格式),例如:time()

echo $data['end']->format(DateTime::W3C);//echoes Y-m-dTH:i:s+01:00)
//or, a cookie-formatted time:
echo $data['end']->format(DateTime::COOKIE);//Wednesday, 02-Oct-13 12:42:01 GMT

注意:我将+01:00GMT基于您的转储,将伦敦显示为您的时区...

所以:

$now = new DateTime;
$timestamp = time();
echo $now->getTimetamp(), ' ~= ', $now;//give or take, it might be 1 second less
echo $now->format('c'), ' or ', $now->format('Y-m-d H:i:s');

阅读手册,玩一会,你很快就会找到这个DateTime类,它所有的相关类(比如DateIntervalDateTimeImmutable等等(完整列表在这里))确实是非常方便的东西......

我整理了一个小键盘作为示例,代码如下:

$date = new DateTime('now', new DateTimeZone('Europe/London'));
$now = time();
if (!method_exists($date, 'getTimestamp'))
{//codepad runs <PHP5.3, so getTimestamp method isn't implemented
    class MyDate extends DateTime
    {//bad practice, extending core objects, but just as an example:
        const MY_DATE_FORMAT = 'Y-m-d H:i:s';
        const MY_DATE_TIMESTAMP = 'U';
        public function __construct(DateTime $date)
        {
            parent::__construct($date->format(self::MY_DATE_FORMAT), $date->getTimezone());
        }
        /**
         * Add getTimestamp method, for >5.3
         * @return int
         **/
        public function getTimestamp()
        {//immediatly go to parent, don't use child format method (faster)
            return (int) parent::format(self::MY_DATE_TIMESTAMP);
        }
        /**
         * override format method, sets default value for format
         * @return string
         **/
        public function format($format = self::MY_FORMAT)
        {//just as an example, have a default format
            return parent::format($format);
        }
    }
    $date = new MyDate($date);
}
echo $date->format(DateTime::W3C), PHP_EOL
     ,$date->format(DateTime::COOKIE), PHP_EOL
     ,$date->getTimestamp(), ' ~= ', $now;
于 2013-10-02T11:28:23.867 回答