PHP でタイムゾーンを明示して日時を扱う

概要

日時はIANAタイムゾーン名を明示し、可変なDateTimeよりDateTimeImmutableを基本にします。サーバー設定とアプリケーションの前提も揃えます。

実施例

date_default_timezone_set('Asia/Tokyo');

$now = new DateTimeImmutable('now', new DateTimeZone('Asia/Tokyo'));
echo $now->format('Y-m-d H:i:s P');

注意点

保存はUTC、表示時に利用者のタイムゾーンへ変換する設計が扱いやすいです。

参考: 公式ドキュメント