How to generate List of previous 6 months with year from DateTime.Now

You can create the list of DateTime values using an Enumerable.Range lambda expression. You will need to extract the month/year strings using ToString("MM/yyyy") on each value in the enumeration. Take a look at this fiddle for a working example: https://dotnetfiddle.net/5CQNnZ


var lastSixMonths = Enumerable.Range(0, 6)
                              .Select(i => DateTime.Now.AddMonths(i - 6))
                              .Select(date => date.ToString("MM/yyyy"));

This is all you need.

var now = DateTimeOffset.Now;
ViewBag.Months = Enumerable.Range(1, 6).Select(i => now.AddMonths(-i).ToString("MM/yyyy"));

Example Output (as of February 2016):

01/2016 
12/2015 
11/2015 
10/2015 
09/2015 
08/2015 

You don't strictly need to set the now variable first, but it does serve to ensure that you don't roll over to a new month in the middle of processing. It would be an extremely unlikely bug, but could potentially happen.

Tags:

C#

Asp.Net Mvc