PHP の DateTime で月初と月末の取得


検索すると date と strtotime の組み合わせでの記事が多いので、DateTime の記述例を記載。

// 今月
$firstThisMonthObj = new DateTime( 'first day of this month' );
$lastThisMonthObj  = new DateTime( 'last day of this month' );

// 来月
$tmpObj            = new DateTime( 'first day of this month' );
$tmpObj           -> modify( '+1 month' );
$tmpFormat         = $tmpObj -> format( 'Y-m' );
$firstNextMonthObj = new DateTime( 'first day of '.$tmpFormat );
$lastNextMonthObj  = new DateTime( 'last day of '.$tmpFormat );

可能であれば

// 来月
$firstNextMonthObj = new DateTime( 'first day of next month' );
$lastNextMonthObj  = new DateTime( 'last day of next month' );

と記述したいところだけど「今日」が月末になったとき、おかしな動きをするのではないかと懸念がありまして。ただ、検証はしていません。

[mokurenCB]