PHP タイムスタンプを DateTime に変換する 質問する

PHP タイムスタンプを DateTime に変換する 質問する

これをstrtotimeや同様の型の値に変換して渡す方法をご存知ですか?日付時刻物体?

私が持っている日付:

Mon, 12 Dec 2011 21:17:52 +0000

私が試したこと:

$time = substr($item->pubDate, -14);
$date = substr($item->pubDate, 0, strlen($time));

$dtm = new DateTime(strtotime($time));
$dtm->setTimezone(new DateTimeZone(ADMIN_TIMEZONE));
$date = $dtm->format('D, M dS');
$time = $dtm->format('g:i a');

上記は正しくありません。多数の異なる日付をループすると、すべて同じ日付になります。

ベストアンサー1

オブジェクトを作成するために文字列をタイムスタンプに変換する必要はありませんDateTime(実際、おわかりのとおり、そのコンストラクターではこれを行うことはできません)。日付文字列をDateTimeそのままコンストラクターに渡すだけです。

// Assuming $item->pubDate is "Mon, 12 Dec 2011 21:17:52 +0000"
$dt = new DateTime($item->pubDate);

そうは言っても、文字列の代わりにタイムスタンプを使いたい場合は、次のようにします。DateTime::setTimestamp():

$timestamp = strtotime('Mon, 12 Dec 2011 21:17:52 +0000');
$dt = new DateTime();
$dt->setTimestamp($timestamp);

編集 (2014-05-07):

当時は気づいていなかったのですが、DateTimeコンストラクタするタイムスタンプから直接インスタンスを作成する機能をサポートします。このドキュメント必要なのは、タイムスタンプの先頭に文字を追加することだけです@

$timestamp = strtotime('Mon, 12 Dec 2011 21:17:52 +0000');
$dt = new DateTime('@' . $timestamp);

おすすめ記事