PHPでUTCの日付を現地時間に変換する 質問する

PHPでUTCの日付を現地時間に変換する 質問する

私は UTC 日付を次の方法で DB に保存しています:

$utc = gmdate("M d Y h:i:s A");

そして、保存した UTC 日付をクライアントのローカル時間に変換します。

どうやってやるの?

ありがとう

ベストアンサー1

クライアントがブラウザを意味する場合は、まずブラウザから PHP にタイムゾーン名を送信し、次に以下の説明に従って変換を行う必要があります。

答え

UTCの日時をアメリカ/デンバーに変換する

// create a $dt object with the UTC timezone
$dt = new DateTime('2016-12-12 12:12:12', new DateTimeZone('UTC'));

// change the timezone of the object without changing its time
$dt->setTimezone(new DateTimeZone('America/Denver'));

// format the datetime
$dt->format('Y-m-d H:i:s T');

これは、2032 年以降の日付、夏時間、うるう秒で機能し、ホスト マシンのロケールやタイムゾーンに依存しません。

計算にはタイムゾーンデータベースを使用します。このデータベースは、タイムゾーンのルールが変わると時間とともに変化するため、最新の状態に維持する必要があります。(下部の注記を参照)

UTC 日付をサーバー (ローカル) 時間に変換するには、DateTime2 番目の引数 (デフォルトはサーバー タイムゾーン) なしで を使用します。

// create a $dt object with the UTC timezone
$dt = new DateTime('2016-12-12 12:12:12', new DateTimeZone('UTC'));

// get the local timezone
$loc = (new DateTime)->getTimezone();

// change the timezone of the object without changing its time
$dt->setTimezone($loc);

// format the datetime
$dt->format('Y-m-d H:i:s T');

回答2

DateTimeImmutable変数を変更しない (バックグラウンドで変更しない) ため、を使用することをお勧めします。それ以外は と同じように動作しますDateTime

// create a $dt object with the UTC timezone
$dt_utc = new DateTimeImmutable('2016-12-12 12:12:12', new DateTimeZone('UTC'));

// Create a new instance with the new timezone
$dt_denver = $dt_utc->setTimezone(new DateTimeZone('America/Denver'));

// format the datetime
$dt_denver->format('Y-m-d H:i:s T');

不変性により、値を変更せずに複数回チェーンを使用することができます。$dt

$dt = new DateTimeImmutable('2016-12-12 12:12:12', new DateTimeZone('UTC'));

// Format $dt in Denver timezone
echo $dt->setTimezone(new DateTimeZone('America/Denver'))->format('Y-m-d H:i:s T');

// Format $dt in Madrid timezone
echo $dt->setTimezone(new DateTimeZone('Europe/Madrid'))->format('Y-m-d H:i:s T');

// Format $dt in Local server timezone
echo $dt->setTimezone((new DateTime())->getTimezone())->format('Y-m-d H:i:s T');

ノート

time()を返しますUNIXタイムスタンプは数値なので、タイムゾーンはありません。

date('Y-m-d H:i:s T')現在のロケールのタイムゾーンの日付を返します。

gmdate('Y-m-d H:i:s T')UTCで日付を返します

date_default_timezone_set()現在のロケールのタイムゾーンを変更する

タイムゾーンの時間を変更する

// create a $dt object with the America/Denver timezone
$dt = new DateTime('2016-12-12 12:12:12', new DateTimeZone('America/Denver'));

// change the timezone of the object without changing it's time
$dt->setTimezone(new DateTimeZone('UTC'));

// format the datetime
$dt->format('Y-m-d H:i:s T');

ここで利用可能なすべてのタイムゾーンを確認できます

https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

ここにすべての書式設定オプションがあります

http://php.net/manual/en/function.date.php

PHP タイムゾーン DB を更新する (Linux の場合)

sudo pecl install timezonedb

夏時間のため、一部のタイムゾーンでは日付が重複することがあります。たとえば、米国では、2011 年 3 月 13 日午前 2 時 15 分は発生しませんでしたが、2011 年 11 月 6 日午前 1 時 15 分は 2 回発生しました。これらの日付と時刻は正確には判別できません。

おすすめ記事