Receive all months between dates in MM / YYYY format

I want to get all months of the year in a format MM/YYYYbetween two given dates.

Something like that:

Start date: 08/1/2012
End date: 03/1/2013

Result:

09/2012
10/2012
11/2012
12/2012
01/2013
02/2013
03/2013

This is the code that I have, but it does not work as I want.

for (int i = StartDate.Year; i <= EndDate.Year; i++)
{
  for (int j = StartDate.Month+1; j <= 12 ; j++)
  {
    Console.WriteLine(j.ToString("00") + "/" + i.ToString()));
  } 
}

Thank you in advance for your help.

+4
source share
6 answers

There is a possibility that the day value of your starting day will be greater than the daily enddate value. In this case, you need to normalize enddate before the end of the month

List<string> result = new List<string>();
DateTime startDate = new DateTime(2012, 1, 8);
DateTime endDate = new DateTime(2013, 1, 3);
DateTime temp = startDate;
endDate = new DateTime (endDate.Year, endDate.Month, DateTime.DaysInMonth(endDate.Year,endDate.Month));
while (temp <= endDate)
{
    Console.WriteLine((string.Format("{0}/{1}", temp.Month, temp.Year));
    temp = temp.AddMonth(1);
}
+1
source
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"));
}

It will be more readable and reliable if you write a separate counter for dates, for example:

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;
    }
}

What can you name like this:

foreach (var date in MonthsBetween(08, 2012, 03, 2013))
{
    Console.WriteLine(date.ToString("MM/yyyy"));
}

, , .

, .AddMonths(1) , .

( , , .)

+4

for DateTime.AddMonths method like;

DateTime dt1 = new DateTime(2012, 08, 01);
DateTime dt2 = new DateTime(2013, 03, 01);
DateTime dt3 = new DateTime();
for (dt3 = dt1.AddMonths(1); dt3 <= dt2; dt3 = dt3.AddMonths(1))
{
    Console.WriteLine(dt3.ToString("MM/yyyy"));
}

:

09.2012
10.2012
11.2012
12.2012
01.2013
02.2013
03.2013

DEMO.

+1

, :

for (DateTime date = StartDate; date <= EndDate; date = date.AddMonths(1))
    Console.WriteLine(date.ToString("MM/yyyy"));
0

, - :

public IEnumerable<String> EachMonth(DateTime start, DateTime end)
{
    for(var m = start.Date; m.Date <= end.Date; m = m.AddMonths(1))
        yield return m.ToString("MM/YYYY");
}

:

foreach (String month in EachMonth(StartDate, EndDate))
0
DateTime StartDate = Convert.ToDateTime("08/1/2012");
        DateTime EndDate = Convert.ToDateTime("03/1/2013");

        for (DateTime i = StartDate; i <= EndDate; i = i.AddMonths(1))
        {
            Response.Write(i.ToString("MM") + "/" + i.ToString("yyyy")+"<br />");
        }
0

All Articles