find a location for property in a new city

Thursday, 23 September 2010

Get all month names from DateTime in C# programatically

I needed to have a drop down list of all the months but I don't want to be writing all of that out. So is there a way to list all the months programmatically in C#. Hell yeah there is

I knew there would be a way to do it and I knew it would be something to do with the CultureInfo of the session.

Here is a method I wrote to return a set of key values for each month:
public IEnumerable<KeyValuePair<int, string>> GetAllMonths()
{
 for (int i = 1; i <= 12; i++)
 {
  yield return new KeyValuePair<int, string>(i, DateTimeFormatInfo.CurrentInfo.GetMonthName(i));
 }
}

Just to demonstrate, I used it in my ASP.NET MVC app:
<%: Html.DropDownListFor(model => model.DobMonth, new SelectList(Model.GetAllMonths(), "Key", "Value", Model.DobMonth)) %>

Which outputs the following HTML:
<select id="DobMonth" name="DobMonth">
<option selected="selected" value="1">January</option> 
<option value="2">February</option> 
<option value="3">March</option> 
<option value="4">April</option> 
<option value="5">May</option> 
<option value="6">June</option> 
<option value="7">July</option> 
<option value="8">August</option> 
<option value="9">September</option> 
<option value="10">October</option> 
<option value="11">November</option> 
<option value="12">December</option> 
</select>

Follow britishdev on Twitter

5 comments:

  1. OH YEAH !
    Thanks man ! I've been looking for this :)
    i had to add "using System.Globalization;"
    at the beginning of the class...
    ( I'm not in ASP, only in c# though)

    - Any chance the same method could return the month names in french ? :)

    ReplyDelete
  2. Assuming the users' culture isn't already French you could force it by replacing CurrentInfo with GetInstance(new CultureInfo("FR-fr")). So the first bit of code would be:

    public IEnumerable<KeyValuePair<int, string>> GetAllMonths()
    {
    for (int i = 1; i <= 12; i++)
    {
    yield return new KeyValuePair<int, string>(i, DateTimeFormatInfo.GetInstance(new CultureInfo("FR-fr")).GetMonthName(i));
    }
    }

    ReplyDelete
  3. Thank you sir. I used this for Web Form just fine!

    ReplyDelete
  4. thank you so much!

    ReplyDelete

  5. Thanks for posting this useful content, Good to know about new things here, Let me share this, . Hadoop training in pune

    ReplyDelete