PHP関数 date(), getdate() を呼び出すとワーニングが発生し値を取得できない

date関数を呼び出し、結果を画面に表示すると、下図のワーニングメッセージが表示され正しく事項できない場合があります。

現象の確認

下記のPHPファイルをWebブラウザで表示すると、下図のメッセージが表示されます。

コード

<html>
<head>
</head>
<body>
  <?php
  echo date('Y/m/d');  
  ?>
</body>
</html>

表示結果

PHP関数 date(), getdate() を呼び出すとワーニングが発生し値を取得できない:画像1

エラーメッセージ

以下のエラーメッセージが表示されます。

Warning: date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone. in (PHPファイルのパス) on line nn



または、"500 - 内部サーバーエラーです。"のメッセージが表示される場合もあります。
PHP関数 date(), getdate() を呼び出すとワーニングが発生し値を取得できない:画像2

原因

タイムゾーンが設定されていない場合、上記のエラーが発生する場合があります。

対策

date_default_timezone_set('Asia/Tokyo');

を追記し、現在のタイムゾーンを明示的に指定します。

修正後のコード

<html>
<head>
</head>
<body>
  <?php
  date_default_timezone_set('Asia/Tokyo');
  echo date('Y/m/d');  
  ?>
</body>
</html>
AuthorPortraitAlt
著者
iPentecのプログラマー、最近はAIの積極的な活用にも取り組み中。
とっても恥ずかしがり。
作成日: 2014-06-18
Copyright © 1995–2025 iPentec all rights reserverd.