Home > Blockchain >  dd/mm/YYYY format date - while loop problems adding 1 day
dd/mm/YYYY format date - while loop problems adding 1 day

Time:12-08

I am creating a while loop in PHP to iterate through all the days between two dates.

$startdate = "17/12/2022"; // my dd/mm/YYYY format start date
$startdate = str_replace('/', '-',$startdate); // convert the slashes to dashes to signify european date format
$startdate = strtotime($startdate); // convert the date into a date object
$enddate = "16/12/2023"; // my dd/mm/YYYY format start date
$enddate = str_replace('/', '-',$enddate); // convert the slashes to dashes to signify european date format
$enddate = strtotime($enddate); // convert the date into a date object

echo(date('d/m/Y',$startdate)."<br/>");
echo(date('d/m/Y',$enddate)."<br/>");

while($startdate <= $enddate) {
    $dayofweek = date('w',$startdate); // a task
    echo($dayofweek)."<br/>");
    //I need to increment the $startdate by one day here?
}
?>

I believe that changing the slashes to dashes effectively instructs PHP to recognise the date as dd/mm/YYYY rather than mm/dd/YYYY.

I then convert both dates to a date object using strtotime so that they can be compared.

I then need to add 1 day to the $startdate and loop, but it is the adding one day that is foxing me. All the examples I can find are using todays date or a string not formatted dd/mm/YYYY.

I freely admit that I may have got the whole premise wrong but any pointers for good practise would be appreciated.

CodePudding user response:

Using the DateTime class and the DateInterval Class and the DatePeriod class you get quite a bit of the heavy lifting done for you

$startdate = "17/12/2022"; // my dd/mm/YYYY format start date
$enddate = "31/12/2022"; // my dd/mm/YYYY format start date

$sDate = ( new Datetime() )->createFromFormat('d/m/Y', $startdate);
$eDate = ( new Datetime() )->createFromFormat('d/m/Y', $enddate);

$oneDay = new DateInterval('P1D');
$daterange = new DatePeriod($sDate, $oneDay ,$eDate);

foreach ( $daterange as $dat) {
    echo $dat->format('d/m/y - w D') . PHP_EOL;
}

RESULTS using a smaller range of dates

17/12/22 - 6 Sat
18/12/22 - 0 Sun
19/12/22 - 1 Mon
20/12/22 - 2 Tue
21/12/22 - 3 Wed
22/12/22 - 4 Thu
23/12/22 - 5 Fri
24/12/22 - 6 Sat
25/12/22 - 0 Sun
26/12/22 - 1 Mon
27/12/22 - 2 Tue
28/12/22 - 3 Wed
29/12/22 - 4 Thu
30/12/22 - 5 Fri

  • Related