user2118542
user2118542

Reputation:

Get all months and years between two datetime

What I need is to get logic on how to get monthname-year between two dates.

Dictionary<Monthname,year> GetMonthsandYear(Datetime d1,Datetime d2) 
       or
List<Tuple<string,int> GetMonthsandYear(Datetime d1,Datetime d2)

example : jan-1-2013 to mar-3-2013

should return January-2013,february-2013,march-2013 or in reverse format by list.reverse

Upvotes: 3

Views: 6698

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1504002

If your actual requirement is "the previous 24 months" then it's much simpler. Just start off with the current month, and get the 1st day of it - then iterate and add 1 month 24 times.

Personally I'd return an IEnumerable<DateTime> rather than anything else - you can format each element however you want - but it's pretty simple:

public static IEnumerable<DateTime> GetMonths(int count)
{
    // Note: this uses the system local time zone. Are you sure that's what
    // you want?
    var today = DateTime.Today;
    // Always return the 1st of the month, so we don't need to worry about
    // what "March 30th - 1 month" means
    var startOfMonth = new DateTime(today.Year, today.Month, 1);
    for (int i = 0; i < count; i++)
    {
        yield return startOfMonth;
        startOfMonth = startOfMonth.AddMonths(-1);
    }
}

Then if you want a List<string> of these values as "February 2014" etc for example, you could have:

var monthYears = GetMonths(24).Select(dt => dt.ToString("MMMM yyyy"))
                              .ToList();

Note that a Dictionary<...> would not be appropriate unless you really don't care about the order - and I suspect you do. You shouldn't rely on the order in which items are returned from a Dictionary<TKey, TValue> when you view it as a sequence - it's not intended to be an ordered collection.

Upvotes: 7

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98868

I don't understand why you need Dictionary or List<Tuple<string,int> but one solution could be;

DateTime dt1 = new DateTime(2013, 1, 1);
DateTime dt2 = new DateTime(2013, 3, 3);

while (dt1 < dt2)
{
    Console.WriteLine(dt1.ToString("MMMM-yyyy"));
    dt1 = dt1.AddMonths(1);
}

Result will be;

January-2013
February-2013
March-2013

Even if you need, you can add these values to a List<string> in while loop.

But be carefull about what Jon said, this solution will generate only January and February if your dt1.Day is greater than dt2.Day.

Upvotes: 5

Related Questions