「日付をFor文で1日ずつループで回すには」
開始日と終了日を指定して日付をFor文で1日ずつループで回すには?
strtotime関数、
date関数
回答
日付文字列をstrtotime関数でunixtime(Unix時間)に変換すれば、for文で回すことが出来ます。
Unix時間とは
協定世界時 (UTC) の1970年1月1日午前0時0分0秒(UNIXエポック)からの経過秒数のことです。
1日の秒数(60秒×60分×24時=86400秒)ずつ足し算してループすれば、1日ごとにループできます。
ソース
//例1
//2020年01月01日~2021年12月31日までfor文で回す場合
$startDate=strtotime("20200101");
$endDate =strtotime("20211231");
$secondsOfOneDay=60*60*24; //1日あたりの秒数
for($i=$startDate;$i<=$endDate;$i+=$secondsOfOneDay){
echo date("Ymd",$i).PHP_EOL;
}
//例2
//2020年01月01日~2021年12月31日までfor文で回す場合
$s=strtotime("2020-01-01");
$e=strtotime("2021-12-31");
$secondsOfOneDay=60*60*24; //1日あたりの秒数
for($i=$startDate;$i<=$endDate;$i+=$secondsOfOneDay){
echo date("Y-m-d",$i).PHP_EOL; //"Y-m-d"でもOK
}