PHPで対象月の月初や月末の日付を取得する
よくわからないまま、次の月の初日をまず取得してから-1日してゴニョゴニョ、とかやっていましたが、もっと簡単に書けると知ったのでメモ。
月初を取得する方法
// 当月の月初を取得その1
$firstDate = date('Y/m/01');
echo $firstDate; // 2018/08/01
// 当月の月初を取得その2
$firstDate = date('Y/m/d' , strtotime('first day of'));
echo $firstDate; // 2018/08/01
// 指定月の月初を取得その1
$firstDate = date('Y/m/01', strtotime('2020-02'));
echo $firstDate; // 2020/02/01
// 指定月の月初を取得その2
$firstDate = date('Y/m/d' , strtotime('first day of 2020-02'));
echo $firstDate; // 2020/02/01
月末を取得する方法
// 当月の月末を取得その1
$lastDate = date('Y/m/t');
echo $lastDate; // 2018/08/31
// 当月の月末を取得その2
$lastDate = date('Y/m/d' , strtotime('last day of'));
echo $lastDate; // 2018/08/31
// 指定月の月末を取得その1
$lastDate = date('Y/m/t', strtotime('2020-02'));
echo $lastDate; // 2020/02/29
// 指定月の月末を取得その2
$lastDate = date('Y/m/d' , strtotime('last day of 2020-02'));
echo $lastDate; // 2020/02/29