0

I'm trying to print dates between two other dates. Here is my code:

$begin = date("d/m/y");
$end = date("d/m/y", strtotime("+1 month"));

$i = 0;
while( strtotime($begin) <= strtotime($end) ){

    echo "$begin\n";

    $i++;
    $begin = date("d/m/y", strtotime("+$i day") );

}

You can execute the same code here: http://sandbox.onlinephpfunctions.com/code/34c4b721553038f585806798121941bee0c66086

For some reason this code is printing just the dates between 25/01/2017 and 31/01/2017 instead of 25/01/2017 and 25/02/2017. I don't know what's wrong. Can someone help me?

Breno Macena
  • 449
  • 8
  • 19
  • Dont get me wrong, but why are you using `date()` here? It can be done only with `strtotime()`. And you will call less functions in the iteration. – JustOnUnderMillions Jan 25 '17 at 15:36

2 Answers2

2

strtotime() doesn't support dates in d/m/y format. It treats these dates as m/d/y.

To fix your code, use Y-m-d format in the first two lines.

On a sidenote, I'd recommend to use \DateTime classes to manipulate dates instead of strings and integers. Read more here: https://paulund.co.uk/datetime-php

Bartosz Zasada
  • 3,762
  • 2
  • 19
  • 25
2
<?php
error_reporting(-1);
ini_set('display_errors', true);

$begin = new DateTime();
$end = (new DateTime())->modify('+1 month');
$interval = DateInterval::createFromDateString('1 day');

$period = new DatePeriod($begin, $interval, $end);

foreach ($period as $date) {
    echo $date->format('d/m/y')."<br/>";
}
Vitalij Mik
  • 542
  • 3
  • 6