-2

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!

Fabrizio Mazzoni
  • 1,831
  • 2
  • 24
  • 46
  • 3
    We are always glad to help and support new coders but you need to help yourself first. You are expected to try to write the code yourself. Please read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – brombeer Feb 21 '19 at 07:43

3 Answers3

3

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.

naththedeveloper
  • 4,503
  • 6
  • 36
  • 44
3

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'));
}
dWinder
  • 11,597
  • 3
  • 24
  • 39
0

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));

https://3v4l.org/S3AK5

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).

JustCarty
  • 3,839
  • 5
  • 31
  • 51