[PHP]指定日時からn日前、n日後、来年などの日付を計算する

DateTimeクラスを利用して指定した日時から1日後や3年前の日付を計算する。その他にも指定月の一番最初に日や、月末の日を取得することができる。

phpのバージョンが5.2以上の場合はDateTimeクラスを推奨。

・サンプルコード

$date = new DateTime();
echo '一日後・・・・・・・・・'.$date->modify('+1 days')->format('Y-m-d H:i:s');
echo '<br>';

$date = new DateTime();
echo '一日前・・・・・・・・・'.$date->modify('-1 days')->format('Y-m-d H:i:s');
echo '<br>';

$date = new DateTime();
echo '六時間後・・・・・・・・'.$date->modify('+6 year')->format('Y-m-d H:i:s');
echo '<br>';

$date = new DateTime();
echo '一週間後・・・・・・・・'.$date->modify('+1 weeks')->format('Y-m-d H:i:s');
echo '<br>';

$date = new DateTime();
echo '四ヶ月六日三時間後・・・'.$date->modify('+4 months +6 days +3 hours')->format('Y-m-d H:i:s');
echo '<br>';

$date = new DateTime();
echo '正午・・・・・・・・・・'.$date->modify('noon')->format('Y-m-d H:i:s');
echo '<br>';

$date = new DateTime();
echo '当月一日・・・・・・・・'.$date->modify('first day of this months')->format('Y-m-d H:i:s');
echo '<br>';

$date = new DateTime();
echo '当月末尾・・・・・・・・'.$date->modify('last day of this months')->format('Y-m-d H:i:s');
echo '<br>';

$date = new DateTime();
echo '来月一日・・・・・・・・'.$date->modify('first day of next months')->format('Y-m-d H:i:s');
echo '<br>';

$date = new DateTime();
echo '先月一日・・・・・・・・'.$date->modify('first day of last months')->format('Y-m-d H:i:s');
echo '<br>';

$date = new DateTime();
echo '次の日曜日・・・・・・・'.$date->modify('sunday')->format('Y-m-d H:i:s');
echo '<br>';

$date = new DateTime();
echo '今週の月曜日・・・・・・'.$date->modify('monday this week')->format('Y-m-d H:i:s');
echo '<br>';

$date = new DateTime();
echo '第三日曜日・・・・・・・'.$date->modify('third sunday of this months')->format('Y-m-d H:i:s');
echo '<br>';

・実行結果

phpのバージョンが満たない場合はstrtotime()関数を使うことで日付の計算ができる。
ただし「2038年問題」で使えなくなるので非推奨。

・サンプルコード

$target_date = date('Y-m-d H:i:s', time());
echo '現在・・・・'.$target_date.'<br>';

$result = date('Y-m-d H:i:s', strtotime('-1 year', strtotime($target_date)));
echo '一年前・・・'.$result.'<br>';

$result = date('Y-m-d H:i:s', strtotime('-3 day', strtotime($target_date)));
echo '三日前・・・'.$result.'<br>';

$result = date('Y-m-d H:i:s', strtotime('+4 month', strtotime($target_date)));
echo '四ヶ月後・・'.$result.'<br>';

・実行結果

以上です。

コメントする

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です