user813995 user813995 - 7 months ago 15
PHP Question

Fetching data between Start date to end date

$startMonth = strtotime(2011-02-20);
$endMonth = strtotime(2011-06-05);
while($startMonth <= $endMonth)
{
echo date('F Y', $startMonth);
$startMonth = strtotime("+1 month", $startMonth);
}


I have a problem while fetching data between start and end date using the code above.
If i run this code it's just able to fetch the data between 02[feb] to 05[april] and the 06[june] is omitted. I just want to know what problem is with my code. If i give the dates as 2011-02-01 to 2011-06-01 the output is generated.

problem is like:


  • if i give: '2011-02-01' to '2011-06-01' it works

  • if i give '2011-02-02' to '2011-02-01' it won't work

  • if i give '2011-02-02' to '2011-02-03' it works


Answer

replace

$startMonth = strtotime(2011-02-20);
$endMonth = strtotime(2011-06-05);

with

$startMonth = strtotime('2011-02-20');
$endMonth = strtotime('2011-06-05');

You need to clearly set that date is string value, because PHP makes calculation and replaces 2011-02-20 with 1989 (2011 minus 2 minus 20)

---added---

Ok, one more variant (hope I understand what you want to see )

<?php
$startMonth = strtotime(date("01-n-Y",strtotime('2011-02-20')));
$endMonth = strtotime(date('01-n-Y',strtotime('2011-06-05')));
  while($startMonth <= $endMonth)
     {
           echo date('F Y', $startMonth);
           $startMonth = strtotime("+1 month", $startMonth);
     }
?>