简体   繁体   中英

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

I am very new to .net MVC. How can I generate list of last 6 months with years in .net MVC. The only thing have is DateTime.Now and i need

ViewBag.Months=List of months with years

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM