備忘録

備忘録

PHP 日付(日時)加算、減算まとめ

2022/02/21追記

本記事内容は古い
DateTime/DateTimeImmutableを利用した方法がモダン

はじめに

減算は「+」を「-」に変えるだけ

まとめ

<?php
// 現在日時
// 出力: 2016/10/27 08:33:33
echo date('Y/m/d H:i:s');

// 現在日時
// 出力: 2016/10/27 08:33:33
$unixtime = time();
echo date('Y/m/d H:i:s', $unixtime);

// $unixtimeを「1時間」進める
$unixtime = time();
return date('Y/m/d H:i:s', strtotime('+1 hour', $unixtime));

// 現在日時を「1秒」進める
// 出力: 2016/10/27 08:33:34
echo date('Y/m/d H:i:s', strtotime('+1 second'));

// 現在日時を「1分」進める
// 出力: 2016/10/27 08:34:33
echo date('Y/m/d H:i:s', strtotime('+1 minute'));

// 現在日時を「1時間」進める
// 出力: 2016/10/27 09:33:33
echo date('Y/m/d H:i:s', strtotime('+1 hour'));

// 現在日時を「1日」進める
// 出力: 2016/10/28 08:33:33
echo date('Y/m/d H:i:s', strtotime('+1 day'));

// 現在日時を「1ヶ月」進める
// 出力: 2016/11/27 08:33:33
echo date('Y/m/d H:i:s', strtotime('+1 month'));

// 現在日時を「1年」進める
// 出力: 2017/10/27 08:33:33
echo date('Y/m/d H:i:s', strtotime('+1 year'));

// 現在日時を「1年」と「1ヶ月」進める
// 出力: 2017/11/27 08:33:33
echo date('Y/m/d H:i:s', strtotime('+1 year +1 month'));

// 「2016/10/27 08:33:33」を「1年」と「1ヶ月」進める
// 出力: 2017/11/27 08:33:33
echo date('Y/m/d H:i:s', strtotime('2016/10/27 08:33:33' . '+1 year +1 month'));

// 「2022/01/01」の「月末」を出力する
echo date('Y/m/t', strtotime("2022/01/01 00:00:00"));