[PHP] 月初・月末の日付を取得する方法(date strtotime)

PHPで月初と月末の日付を取得する方法についてです。
「strtotime()」と「date()」いう関数を使います。

strtotime()とdate()関数を使った取得方法

$month = '2015-02'; 
$firstDay = date('Y-m-d', strtotime('first day of' . $month));
$lastDay = date('Y-m-d', strtotime('last day of' . $month));
echo '月初は「'.$firstDay.'」で、月末は「'.$lastDay.'」です。';

↓プログラム実行結果

月初は「2015-02-01」で、月末は「2015-02-28」です。

date()関数を使った取得方法

当月の月初・月末の日付の取得はdate()関数でもできます。

//月初
$firstDay=date("Y-m-01");
 
//月末
$lastDay=date("Y-m-t");

//出力
echo '月初は「'.$firstDay.'」で、月末は「'.$lastDay.'」です。';

月初は1日なので01を指定。
月末の日にちはtで取得することができます。

↓プログラム実行結果

月初は「2015-02-01」で、月末は「2015-02-28」です。


Author: webmaster