Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net-mvc

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

like image 713
Parth Ruparelia Avatar asked Feb 09 '16 13:02

Parth Ruparelia


People also ask

How to get the year from a DateTime in c#?

string year = DateTime. Parse(DateTime. Now. ToString()).

How to get previous year in c#?

Try the following: DateTime. AddYears(-1);

How do I get the first day of the last month in C#?

AddMonths(-1); var last = month. AddDays(-1);


2 Answers

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"));
like image 150
JTW Avatar answered Nov 07 '22 10:11

JTW


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.

like image 20
Chris Pratt Avatar answered Nov 07 '22 12:11

Chris Pratt