for
(
DateTime date = new DateTime(2012, 08, 01).AddMonths(1);
date <= new DateTime(2013, 03, 01);
date = date.AddMonths(1)
)
{
Console.WriteLine(date.ToString("MM/yyyy"));
}
This would be more readable and robust if you write a separate enumerator for the dates, like so:
public static IEnumerable<DateTime> MonthsBetween(int startMonth, int startYear, int endMonth, int endYear)
{
for
(
DateTime date = new DateTime(startYear, startMonth, 01).AddMonths(1);
date <= new DateTime(endYear, endMonth, 01);
date = date.AddMonths(1)
)
{
yield return date;
}
}
Which you could call like so:
foreach (var date in MonthsBetween(08, 2012, 03, 2013))
{
Console.WriteLine(date.ToString("MM/yyyy"));
}
Note that this range excludes the first month, which from your example it seems you want.
If you don't want to skip the first month, remove the .AddMonths(1)
from the line creating the start date.
(Personally, I'd prefer to include the starting month in the output, but that is not what you asked for.)