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プロパティがありませ。ただし、マニュアルと同様getTimestampに、int を返すメソッドがあります。 定義済みの定数 (標準形式を表すすべての文字列) を使用できます。次に例を示します。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 に答える