LoginSignup
91
83

More than 1 year has passed since last update.

PHPで月末日を取得する

Last updated at Posted at 2014-01-29

概説

タイトルの通り、PHPで月末日を取得します。

今月の末日を取得する

PHP
echo (new DateTimeImmutable)->modify('last day of')->format('Y-m-d'); // 2021-03-31

先月の末日を取得する

PHP
echo (new DateTimeImmutable)->modify('last day of last month')->format('Y-m-d'); // 2021-02-28

翌月の末日を取得する

PHP
echo (new DateTimeImmutable)->modify('last day of next month')->format('Y-m-d'); // 2021-04-30

指定月の末日を取得する

PHP
echo (new DateTimeImmutable)->modify('last day of 2020-02')->format('Y-m-d'); // 2020-02-29
echo (new DateTimeImmutable)->modify('last day of 2019-02')->format('Y-m-d'); // 2019-02-28

これより以降は以前投稿していた古い内容になります。参考程度にご覧ください。


今月の末日を取得する

PHP
echo date('Y-m-t'); // 2014-01-31

もしくは

echo date('Y-m-d', mktime(0, 0, 0, date('m') + 1, 0, date('Y'))); // 2014-01-31

先月の末日を取得する

PHP
echo date('Y-m-d', mktime(0, 0, 0, date('m'), 0, date('Y'))); // 2013-12-31

翌月の末日を取得する

PHP
echo date('Y-m-d', mktime(0, 0, 0, date('m') + 2, 0, date('Y'))); // 2014-02-28

失敗するパターン

なお、strtotimeの引数で'+1 month'、'-1 month'を利用すると見ばえよく書けそうですが、2月の周辺で期待通りの動作をしない場合がある注意が必要です。
この件については、マニュアルでもイロイロと言及されているので、ぜひご一読を。

PHP
echo date('Y-m-d', strtotime('2014-01-29 +1 month')); // 2014-03-01
echo date('Y-m-d', strtotime('2014-03-31 -1 month')); // 2014-03-03

月初の日付に対して'+1 month'、'-1 month'してあげるとうまくいくということを教えてもらったので、strtotimeを利用した方法を追記しておきます。

先月の末日を取得する

PHP
date('Y-m-t', strtotime(date('Y-m-01') . '-1 month')); // 2013-12-31

翌月の末日を取得する

PHP
date('Y-m-t', strtotime(date('Y-m-01') . '+1 month')); // 2014-02-28

参考URL

91
83
3

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
91
83