Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

easy way to loop over months and years from a given date

Tags:

date

c#

I have been trying to write this loop and it just keeps getting more complicated. Basically I want to take a given date and loop through every month until I reach the current month. So if the start date is 11/1/2011 then I want to loop through

11/2011, 12/2011, 1/2012, 2/2012, etc.

Here is what I started with but this does not work. Once I hit a new year I need the inner loop to start over with 1 not startdate.Month. Is there a better way in general to loop through months and years? Thanks

        for (var y = startdate.Year; y <= DateTime.Now.Year; y++)
        {
            for (var m = startdate.Month; m <= 12; m++)
            {
                  //do something with m and y
            }
        }
like image 287
Rochelle C Avatar asked Nov 07 '13 02:11

Rochelle C


4 Answers

Date target = new Date(2011, 4, 1);
while (target < Date.Today) {
  // do something with target.Month and target.Year
  target = target.AddMonths(1);
}
like image 143
Sam Axe Avatar answered Nov 04 '22 08:11

Sam Axe


DateTime endDate = DateTime.Today;
for (DateTime dt = startDate; dt <= endDate; dt = dt.AddMonths(1))
{
    Console.WriteLine("{0:M/yyyy}", dt);
}

But if you prefer while loops, then vote for Dan-o. I did. :)

like image 39
Matt Johnson-Pint Avatar answered Nov 04 '22 08:11

Matt Johnson-Pint


Sam's answer is nice but ultimately incorrect (if your start day is 20 and your end day is 10, it won't include the last month). Here's a version that works:

    public void GetMonths(DateTime startTime, DateTime endTime)
    {
        var dateCounter = new DateTime(startTime.Year, startTime.Month, 1);
        var endDateTarget = new DateTime(endTime.Year, endTime.Month, 1);

        while (dateCounter <= endDateTarget)
        {
            Console.WriteLine($"The year and month is: {dateCounter.Year}, {dateCounter.Month}");
            dateCounter = dateCounter.AddMonths(1);
        }
    }
like image 20
Slothario Avatar answered Nov 04 '22 08:11

Slothario


This will loop over the months and the day of the month will not be a problem.

var date = startDate;
var endDate = DateTime.Now;

while(date.Year < endDate.Year || (date.Year == endDate.Year && date.Month <= endDate.Month))
{
    Console.WriteLine($"{date.Month}/{date.Year}");
    date = date.AddMonths(1);
}
like image 2
Hüseyin Yağlı Avatar answered Nov 04 '22 07:11

Hüseyin Yağlı