[PHP] 月末の日付を取得する

MacのshellはこちらLinuxのshellはこちら
PHPで日付を算出するには date を利用します。何も指定しなければ、現時点の日時となります。

echo date('Y-m-d'); // 当日
echo date('Y-m-t'); // 月末
echo date('Y-m-01'); // 月初

当日から算出する場合は last day が使えます。

echo date('Y-m-d', strtotime('last day of -2 month'));
echo date('Y-m-d', strtotime('last day of previous month'));
echo date('Y-m-d', strtotime('last day of today'));
echo date('Y-m-d', strtotime('last day of next month'));
echo date('Y-m-d', strtotime('last day of +2 month'));

特定日から算出する場合は、月初の日付を算出してから月末を算出します。

$today = '2023-03-30';
$top = date('Y-m-01', strtotime($today));

echo date('Y-m-t', strtotime($top . " -1 month")); // 1ヶ月前 2023-02-28
echo date('Y-m-t', strtotime($top . " +1 month")); // 1ヶ月後 2023-04-30
echo date('Y-m-t', strtotime($top . " +2 month")); // 2ヶ月後 2023-05-31

3月30日の場合、1ヶ月前が3月の扱いとなってしまうので当日の値をそのまま利用することができません。

$today = '2023-03-30';

echo date('Y-m-t', strtotime($today . " -1 month")); // 1ヶ月前 2023-03-31
echo date('Y-m-t', strtotime($today . " +1 month")); // 1ヶ月後 2023-04-30
echo date('Y-m-t', strtotime($today . " +2 month")); // 2ヶ月後 2023-05-31

PHPPHP

Posted by kidatti