LoginSignup
4
4

More than 5 years have passed since last update.

タイムゾーンの変換 (MySQLとPHPによる方法)

Posted at

とあるタイムゾーンの時間を他のタイムゾーンの時間に変換する。
Daylight Saving Time(サマータイム) とかも考慮する。

といった時に使える方法。

MySQLのを使った方法

SELECT CONVERT_TZ('2016-08-29 00:00:00', 'America/Los_Angeles', 'UTC') AS time; // PDT
SELECT CONVERT_TZ('2016-01-29 00:00:00', 'America/Los_Angeles', 'UTC') AS time; // PST

結果

+---------------------+
| time                |
+---------------------+
| 2016-08-29 07:00:00 |
+---------------------+

+---------------------+
| time                |
+---------------------+
| 2016-01-29 08:00:00 |
+---------------------+

CONVERT_TZ が NULLを返す場合は zoneinfo から mysql.time_zone にデータを入れる必要がある
参考:

PHPを使った方法

function convert_tz($time, $from_tz, $to_tz)
{
    $date = new DateTime($time, new DateTimeZone($from_tz));
    $date->setTimezone(new DateTimeZone($to_tz));
    return $date->format('Y-m-d H:i:s');
}

echo convert_tz("2016-08-29 00:00:00", "America/Los_Angeles", "UTC")."\n";
echo convert_tz("2016-01-29 00:00:00", "America/Los_Angeles", "UTC")."\n";

結果

2016-08-29 07:00:00
2016-01-29 08:00:00

参考:

4
4
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
4
4