susan
susan

Reputation: 163

How to find previous months using current month in asp.net mvc?

Hi I want to find the Previous month list using Current month.Eg Current month is June -2020 so i want to find the previous month list of june (jan -feb-mar -apr-may-june)in asp .net C#.

 DateTime dt = Globalization.GetShortDateTime.Month;
 DateTime.Now.AddMonths(-1);//This will give just only one previous month eg june.

But I want to find all the previous month of current month and want to store in list. Any one understand my issue and help me to resolve this.Thanks..

Upvotes: -1

Views: 1115

Answers (1)

ingham
ingham

Reputation: 1645

Why not iterating from month 1 to current month ?

var dates = new List<DateTime>();
var now = DateTime.Now;
for (var i = 1; i <= now.Month; i++) {
    //Current year, computed month, day 1, 12:00:00
    var date = new DateTime(now.Year, i, 1, 12, 0, 0);
    dates.Add(date);
}

If what you want is the month name, use this instead:

var dates = new List<string>();
var now = DateTime.Now;
for (var i = 1; i <= now.Month; i++) {
    //Current year, computed month, day 1, 12:00:00
    var date = new DateTime(now.Year, i, 1, 12, 0, 0);
    dates.Add(date.ToString("MMMM"));
}

Upvotes: 2

Related Questions