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
string year = DateTime. Parse(DateTime. Now. ToString()).
Try the following: DateTime. AddYears(-1);
AddMonths(-1); var last = month. AddDays(-1);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With