LoginSignup
16
15

More than 5 years have passed since last update.

PHPで○ヶ月前の日付を求めるプラクティス

Last updated at Posted at 2015-07-02

単純にstrtotime('-1 months')としてしまうと3月31日の場合、2月31日となってしまい正しい値が求められない。

いつも忘れてしまうので、メモしておく。末日を考慮して数ヶ月前の日付を計算する時は以下のように書く。

$ts0331 = strtotime("2015-03-31");
# 1日
date('Y-m-d', strtotime('first day of previous month', $ts0331));
# 末日
date('Y-m-d', strtotime('last day of previous month', $ts0331));

この手の処理は何度も使って人のスキル感によってバグを起こしがちなので注意したい。

追記 2015/07/02

@mpywさんからご指摘頂いた通り修正させていただきました。
皆様フィードバックありがとうございますm(__)m

16
15
6

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
16
15