ど素人から毛を生やす。<延>

DateTimeクラスで「次回の10日」指定は可能?

Web > PHP 2025年12月12日(最終更新:0日前)

どもです。
DateTimeクラスは「前日」とか「1か月後」とかの、「その日を基準として○日」は modify() で簡単にやってくれます。

//前日
(new DateTime())->modify('-1 day');

//1か月後
(new DateTime())->modify('+1 months');

が、「次の‘10日’」のように、一部を指定するケースは、クリティカルな処理が存在しないようです。

しかし DateTime::format() をズルく使えば「今月の○日」といった指定は簡単にできるので…

$now = new DateTime();
if($now->format('d') >= 10){
	//今日が10日より後なら「来月の10日」
	$next = new DateTime((clone $now)->modify('+1 months')->format('Y-m-10'));
}else{
	//今日が10日より前なら「今月の10日」
	$next = new DateTime((clone $now)->format('Y-m-10'));
}

これで「次の‘10日’」が求められました。

さて、この方法で大体の「次の‘○日’」は求められますが、月次第で日が異なる「月末」はどう指定するべきか。

//先月末
(new DateTime())->modify('last day of previous month');

//今月末
(new DateTime())->modify('last day of this month');

これはあるんかい。

$now = (new DateTime())->setTime(0, 0, 0, 0);
if($now->format('Y-m-d') == (clone $now)->modify('last day of this month')->format('Y-m-d')){
	//今日=月末なら「来月の月末」
	$next = (clone $now)->modify('+1 month')->modify('last day of this month');
}else{
	//今日=月末でないなら「今月の月末」
	$next = (clone $now)->modify('last day of this month');
}

じゃあこれでできるか。

この記事は役に立ちましたか?
  • _(:3」∠)_ 面白かった (0)
  • (・∀・) 参考になった (0)
  • (`・ω・´) 役に立った (0)