0
0

More than 1 year has passed since last update.

【PHP】strtotime('+1 month')で次月を求める時には注意が必要

Last updated at Posted at 2022-10-28

はじめに

strtotime('+1 month')を使用して下記のようなプログラムを書いた。

$date = "2022-01-31";
var_dump(date('Y-m', strtotime($date.'+1 month'))); // 2022-03
var_dump(date('Y-m', strtotime($date.'+2 month'))); // 2022-03
var_dump(date('Y-m', strtotime($date.'+3 month'))); // 2022-05

ただ、月の日数関係で次月をうまく取得することができなかった…

結論

月に必ず存在している1日を指定することで解決!

// 解決策1
var_dump(date('Y-m', strtotime(date("Y-m-01").'+1 month')));

// 解決策2
var_dump(date('Y-m', strtotime('first day of next month')));

参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0