4

below is my php code to display all date between two dates..but not working properly...

fromdate = 20-04-2015
todate =   25-05-2015

so my code display only 20,21,22,23,24,25

but i need all days between this two months.

expected output

20-04 21-04 22-04 23-04 24-04 25-04 26-04 27-04 28-04  ......upto 25-05

below is my code..

 <?php
    $startdate = $_POST['fromdate'];
    $enddate = $_POST['todate'];
    $start = date('d', strtotime($startdate));
    $end=date('d', strtotime($enddate));
    ?>  

    <?php   for ($x = $start; $x <= $end; $x++) { ?>
        <th width="58%"><?php echo $x; ?></th>
        <?php } ?>
John Conde
  • 217,595
  • 99
  • 455
  • 496
ankit ingle
  • 213
  • 1
  • 5
  • 10

1 Answers1

9

Using strtotime() and date() for traversing dates is not recommended because it is hackish at best. Use DateTime to iterate dates instead:

$start    = new DateTime('20-04-2015');
$end      = (new DateTime('25-05-2015'))->modify('+1 day');
$interval = new DateInterval('P1D');
$period   = new DatePeriod($start, $interval, $end);

foreach ($period as $dt) {
    echo $dt->format("d-m") . "<br>\n";
}

Demo

For PHP < 5.4 (echo phpversion();), which doesn't support array dereferencing:

Demo

The above code creates DateTime objects for the start and end date. We have to add one day to the end date as it will not be included in our loop later on. It then creates a DateInterval object to represent the increment of one day and a DatePeriod object to contain it all. It then loops through each date and echos out the date in the format you expect.

Community
  • 1
  • 1
John Conde
  • 217,595
  • 99
  • 455
  • 496