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

I am very new to .net MVC. How can I create a list of the last 6 months over the years in .net MVC. The only thing there is is DateTime.Now, and I need

ViewBag.Months=List of months with years

+7
source share
2 answers

You can create a list of DateTime values ​​using the Enumerable.Range lambda expression. You will need to extract the month / year strings using ToString ("MM / yyyy") for 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"));
+23
source

That 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 

now, , . , .

+6

Source: https://habr.com/ru/post/1627965/


All Articles