0

So what I am looking to do is to get future six months in a dropdown box and I was trying something like

        public List<String> GetTrainingDates()
    {
        var monthList = new List<String>();
        var currentMonth = DateTime.Now.Month;
        for(var i = currentMonth; i <= currentMonth + 6; i++)
        {
            monthList.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i));
        }
        return monthList;
    }

But ofcourse this goes greater than 12, so would have to restart at 12 and then start from 1 again.

Just wondering if anybody has a good idea how to do this ?

numerah
  • 498
  • 7
  • 29
StevieB
  • 6,263
  • 38
  • 108
  • 193
  • Possible duplicate: http://stackoverflow.com/questions/812330/what-is-the-best-way-to-code-up-a-month-and-year-drop-down-list-for-asp-net – Adil Aug 01 '12 at 15:45

4 Answers4

3

Just use the % modulus operator:

monthList.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(
               ((i - 1) % 12) + 1));
Oded
  • 489,969
  • 99
  • 883
  • 1,009
2
    public List<String> GetTrainingDates()
        {
            var monthList = new List<String>();
            var currentDate = DateTime.Now();
            for(var i = 0; i <= 6; i++)
            {              
                monthList.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(currentDate.AddMonths(i).Month));
            }
            return monthList;
        }
Curtis
  • 101,612
  • 66
  • 270
  • 352
0

Use the .AddMonths function of the DateTime class...

public List<String> GetTrainingDates()
{
    var monthList = new List<String>();
    var month;
    for(var i = 1; i <= 6; i++)
    {
       month = DateTime.Now.AddMonths(i).Month;
       monthList.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(month));
    }
    return monthList;
}
freefaller
  • 19,368
  • 7
  • 57
  • 87
0

Simply, you can use LINQ expression with Range.....

 List<string> listMonth = Enumerable.Range(1, 6).ToList()
                             .Select(i => CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.AddMonths(i).Month))
                             .ToList();
Akash KC
  • 16,057
  • 6
  • 39
  • 59