tags:

views:

882

answers:

6

At the moment I'm creating a DateTime for each month and formatting it to only include the month. Is there another or a better way to do this?

+3  A: 

You can use the following to return an array of string containing the month names

System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
Rohan West
+18  A: 

You can use the DateTimeFormatInfo to get that information:

string name = DateTimeFormatInfo.GetMonthName(1); // Will return January

or to get all names:

string[] names = DateTimeFormatInfo.MonthNames;

http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx

Y Low
+2  A: 

You can get a list of localized months from Thread.CurrentThread.CurrentCulture.DateTimeFormat.MonthNames and invariant months from DateTimeFormatInfo.InvariantInfo.MonthNames.

string[] localizedMonths = Thread.CurrentThread.CurrentCulture.DateTimeFormat.MonthNames;
string[] invariantMonths = DateTimeFormatInfo.InvariantInfo.MonthNames;

for( int month = 0; month < 12; month++ )
{
    ListItem monthListItem = new ListItem( localizedMonths[month], invariantMonths[month] );
    monthsDropDown.Items.Add( monthListItem );
}

There might be some issue with the number of months in a year depending on the calendar type, but I've just assumed 12 months in this example.

Greg
For some reason the code I grabbed was using the Invariant name for the ListItem.Value property. Not sure why, but you might want to use an integer for that instead.
Greg
+2  A: 

Try enumerating the month names:

for( int i = 1; i <= 12; i++ ){
  combo.Items.Add(CultureInfo.CurrentCulture.DateTimeFormat.MonthNames[i]);
}

It's in the System.Globalization namespace.

Hope that helps!

Zachary Yates
+6  A: 

They're defined as an array in the Globalization namespaces.

using System.Globalization;

for (int i = 0; i < 12; i++) {
   Console.WriteLine(CultureInfo.CurrentUICulture.DateTimeFormat.MonthNames[i]);
}
Dylan Beattie
A: 

I did not want to create another question on this topic so posting my question as answer to this question?

Why does DateTimeFormat.MonthNames have 13 values in the array when I try with en-US as the culture?