Having 2 dates (from, to) such as 10/1/2019 and 21/2/2019 how would it be possible to write a loop to print each and every date from the 21st Feb back to the 10th of Jan in reverse order?
Sorry for the dumb question but cannot figure it out!
Having 2 dates (from, to) such as 10/1/2019 and 21/2/2019 how would it be possible to write a loop to print each and every date from the 21st Feb back to the 10th of Jan in reverse order?
Sorry for the dumb question but cannot figure it out!
Just loop over the DateTime objects and output them with a while
loop.
$dt1 = new DateTime('2019-01-28');
$dt2 = new DateTime('2018-10-17');
while($dt1 >= $dt2) {
echo $dt1->format('Y-m-d') . "\r\n";
$dt1->modify('-1 day');
}
Working example: https://3v4l.org/aJ17p
If you want to go the other way between dates just change the dates and change the modify
call to a +1 day
instead.
You can also use DatePeriod
:
$period = new DatePeriod(
new DateTime("10-1-2019"),
new DateInterval('P1D'),
new DateTime("21-2-2019")
);
$res = [];
foreach ($period as $key => $value) { // swap the order of the dates
array_unshift($res,$value->format('Y-m-d'));
}
Here's another alternative.
I would recommend that you actually use date library, like in the other answers - I just wanted to add a different approach to the problem.
$start = '10-01-2019';
$end = '21-02-2019';
// This is to progress the range through each day.
// 24 days, 60 minutes, 60 seconds
$step = 24 * 60 * 60;
$days = array_map(function ($day) {
return date('d-M-Y', $day);
}, range(strtotime($end), strtotime($start), -$step));
I convert the day to milliseconds using the strtotime
function.
From there I then step by each day (24 * 60 * 60
) with the range function.
Then it's a simple case of mapping through the array and converting it into a date format (I used d-M-Y
, but there are more here).