PHPプログラムのstrtotime関数で ‘+1 month’ する時の注意点

スポンサーリンク
Webプログラミング

当社の簡易IoTシステムでは、Webブラウザで「装置の稼働履歴」を表示することができます。

この「稼働履歴」を表示するPHPプログラムでは、1ヶ月分の履歴を一覧表示するのですが、8月31日に、表示内容を確認してみたところ、なぜか2ヶ月分(8/1〜9/30)が表示されていました。

そんな訳で、原因を調べました。

表示期間は以下のように、date関数とstrtotime関数を使って求めているのですが、

$btime = strtotime( date("Y/m/01", $target_date) ) ;
$etime = strtotime( date("Y/m/01", strtotime('+1 month', $target_date)) ) ;

この、strtotime関数で ‘+1 month’ と指定すると、「8/31の1ヶ月先」→「9/31は存在しないので10/1」と認識されてしまうようです。

以下のように修正して回避しました。8月31日に実行した場合、「8/1の1ヶ月先」→「9/1」と、所望のとおりに認識されます。

$btime = strtotime( date("Y/m/01", $target_date) ) ;
$etime = strtotime( date("Y/m/01", strtotime('+1 month', $btime)) ) ;