Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.