PHPでの日付操作(加算減算)・早見

php
目次

date、strtotimeを使った日付操作(加算減算)

date関数とstrtotimeを使って日付を-1日したり、+1日したりする時に使用するロジックです。
たまにド忘れちゃうのでメモとして…

// 現在日付は2024/05/24
// -1日
date("Y/m/d", strtotime("-1 day"));   // 2024/05/23 (1日前)
// -1週間
date("Y/m/d", strtotime("-1 week"));  // 2024/05/17 (1週間前)
// -1ヶ月
date("Y/m/d", strtotime("-1 month")); // 2024/04/24 (1ヶ月前)
// -1年
date("Y/m/d", strtotime("-1 years")); // 2023/05/24 (1年前)

// +1日
date("Y/m/d", strtotime("+1 day"));   // 2024/05/25 (1日後)
// +1週間
date("Y/m/d", strtotime("+1 week"));  // 2024/05/31 (1週間後)
// +1ヶ月
date("Y/m/d", strtotime("+1 month")); // 2024/06/24 (1ヶ月後)
// +1年
date("Y/m/d", strtotime("+1 years")); // 2025/05/24 (1年後)

// 特定の日から日付をプラス・マイナスする
$now_date = "2024/03/01";
date("Y/m/d", strtotime($now_date. "-1 day"));   // 2024/02/29 (うるう年)
date("Y/m/d", strtotime($now_date. "-1 week"));  // 2024/02/23
date("Y/m/d", strtotime($now_date. "-1 month")); // 2024/02/01
date("Y/m/d", strtotime($now_date. "-1 years")); // 2023/03/01
date("Y/m/d", strtotime($now_date. "+1 day"));   // 2024/03/02
date("Y/m/d", strtotime($now_date. "+1 week"));  // 2024/03/08
date("Y/m/d", strtotime($now_date. "+1 month")); // 2024/04/01
date("Y/m/d", strtotime($now_date. "+1 years")); // 2025/03/01

DateTimeクラスを使った日付操作

// ①
// インスタンス化
$DateTime = new DateTime();

$DateTime->modify("-1 day");   // 2024/05/23

$DateTime->modify("-1 week");  // 2024/05/17

$DateTime->modify("-1 month"); // 2024/04/24

$DateTime->modify("-1 year");  // 2023/05/24

$DateTime->modify("+1 day");   // 2024/05/25

$DateTime->modify("+1 week");  // 2024/05/31

$DateTime->modify("+1 month"); // 2024/06/24

$DateTime->modify("+1 year");  // 2025/05/24

$DateTime->format("Y/m/d");    // 最後にフォーマットを指定して取得

// ②
// 特定の日から日付をプラス・マイナスする
$DateTime = new DateTime("2023/05/24");  // 日付を引数に設定

$DateTime->modify("+1 year"); // 2024/05/24 ①同様modifyで調整

$DateTime->format("Y/m/d");   // フォーマットを指定して取得

※補足

1ヶ月の操作は日付が合わない場合があるので注意してください。(内部による仕様)
詳しくは下記の記事で詳しく紹介されているのでご参照ください。
https://zenn.dev/yamatoyo/articles/ab183ecdffa4a

  • URLをコピーしました!
目次