PHPでの日時処理
PHPよく理解してないので整理。日時まわり。
date関数
- 出力したい文字列のフォーマットを受け取り、現在日時(or渡したタイムスタンプ)の日時を、
文字列
で返す - https://www.php.net/manual/ja/function.date.php
echo date('Y-m-d'); // -> 2021-06-01 echo date('Y-m-d H:i:s', 1622419200); -> 2021-05-31 00:00:00
strtotime関数
- 日時文字列を受け取り、
タイムスタンプ(INT)
を返す - シンプルなINTなので、タイムゾーンの情報は持たない。
- https://www.php.net/manual/ja/function.strtotime.php
echo strtotime('2021/05/31 00:00:00'); // -> 1622419200 echo strtotime('now'); // -> 現在日時
日時の加減算
// 現在日時からの加減算 echo date("Y-m-d H:i:s", strtotime("+1 month")); // 指定日時からの加減算 echo date("Y-m-d H:i:s", strtotime('2021-06-02 10:20:30' . "+1 month")); // -> 2021-07-02 10:20:30 // 加減算はタイムスタンプ(INT)の足し引きしてもOK // 月単位の加減算は難しいけど。 $t = strtotime('2021/05/31 00:00:00'); $t += 3600; // 1時間加算 echo date('Y-m-d H:i:s', $t); // -> 2021-05-31 01:00:00
タイムゾーン
// タイムゾーンの確認 echo date_default_timezone_get(); // -> UTC // タイムゾーンの設定 date_default_timezone_set('Asia/Tokyo');