Jump to content

[SOLVED] Incrementing Date Loop


musclehead

Recommended Posts

I'm trying to write a simple loop to generate the date in format YYYY-MM, starting in April 2007 and incrementing to the current date.

 

This probably awful-looking code generates all the months from 04/2007 until today:

 

for ($i = 4; $i < 14; $i++){
  echo date("Y-m",mktime(0,0,0,date("$i"),0,2007))."<br>";       
}

 

If I change the threshold of the "i" variable to 16, the loop will very nicely display January and February of 2008. However, that is a hard-coded value (along w/ the year) and will stop when the month changes to March.

 

I know there's probably something simple to get this script to stop on the current month, but I've been staring at this for too long and can't wrap my head around it anymore! Thanks everyone!

Link to comment
https://forums.phpfreaks.com/topic/88882-solved-incrementing-date-loop/
Share on other sites

<?php
function array_datetotoday($startdate)
{
   $ldate=strtotime($startdate);
   $edate=strtotime(date("Y-m"));
   do
   {
   $dates[]=date("Y-m",$ldate);
   $ldate=strtotime("+1 Month",$ldate);
   }while($ldate <= $edate);
   return $dates;
}

$date_array = array_datetotoday(date("Y-m",strtotime("-1 Year")));
foreach($date_array as $dt)
  echo "$dt<br>";
?>

I realized you said this is "Solved", but here is a solution that uses the strtotime() function:

<?php
$end = time();
$test = strtotime('2007-04-01');
while ($test <= $end) {
    echo date('Y-m',$test) . "<br>\n";
    $test = strtotime('+1 month',$test);
}
?>

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.