LoginSignup
0
0

More than 5 years have passed since last update.

DateTime::SetTimeZoneの挙動が変わった?

Last updated at Posted at 2018-06-23

ほんの少しだけハマった。

PHPで日付を計算するには、DateTimeクラスを使うのが便利です。

そして、UTCで書かれた日付データを日本時間に直す場合などは、SetTimeZoneメソッドを使います。

そこで、SetTimeZoneメソッドですが、公式のヘルプには次のように書かれています。

<?php
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";

$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP') . "\n";
?>

http://jp2.php.net/manual/en/datetime.settimezone.php より引用

ただ、どうもこれだとうまく動きません。setTimeZoneメソッドを使ってもタイムゾーンが変わらないのです。

いろいろ唸ってみた結果、どうも、setTimeZoneの結果が、戻り値にしか反映されていないっぽい

<?php
$date = new DateTime('2000-01-01');
echo $date->setTimezone(new DateTimeZone('Asia/Tokyo'))->format('Y-m-d H:i:sP') . "\n";
?>

PHP 7.2.1のバグなのか、新しい仕様なのかは不明です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0