0
votes

I want to to create somthing like this:

May, 2013
April, 2013
March, 2013
February, 2013
January, 2013
December, 2012
November, 2012

What I have written is this:

var currentDate = DateTime.Now;
var list = new List<ArchiveViewModel>();
for (var startDate = new DateTime(2013, 1, 1); startDate.Month <= currentDate.Month; startDate = startDate.AddMonths(1))
{
    list.Add(new ArchiveViewModel
                {
                    Month = startDate.Month,
                    Year = startDate.Year,
                    FormattedDate = startDate.ToString("MMMM, yyyy")
                });
}

and ArchiveViewModel is this:

public class ArchiveViewModel
{
    public int Month { get; set; }
    public int  Year { get; set; }

    public string  FormattedDate { get; set; }
}

However, it creates only months of a specific year (2012 or 2013):

January, 2013
February, 2013
March, 2013
April, 2013
May, 2013

and if I change the startDate to (2012,1,1) it will create this:

January, 2012
February, 2012
March, 2012
April, 2012
May, 2012

But what I want is this:

November,2012
December , 2012
January, 2013
February, 2013
March, 2013
April, 2013
May, 2013
3

3 Answers

5
votes

Simply change your for loop condition from

startDate.Month <= currentDate.Month

to

startDate <= currentDate
0
votes

try

var currentDate = new DateTime (DateTime.Now.Year, DateTime.Now.Month, 1);

and

for (var startDate = new DateTime(2012, 11, 1); startDate <= currentDate; startDate = startDate.AddMonths(1))
0
votes

Your problem is the stop condition in your for loop

startDate.Month <= currentDate.Month;

currentDate is a constant, and in this case currentDate.Month is always 5. This makes the condition equivalent to

startDate.Month <= 5;

If you try starting later than May (start date in July, for example), it won't loop at all.

I would expand the stop condition to consider the year as well. Something like this:

startDate.Month <= currentDate.Month || startDate.Year < currentDate.Year;

This way, it can loop past May 2012 (since the year will still be less), but will stop at May 2013.