At the moment I\'m creating a DateTime
for each month and formatting it to only include the month.
Is there another or any better way to do this?
public IEnumerable<SelectListItem> Months
{
get
{
return Enumerable.Range(1, 12).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = DateTimeFormatInfo.CurrentInfo.GetMonthName(x)
});
}
}
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!
string[] monthNames = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;
foreach (string m in monthNames) // writing out
{
Console.WriteLine(m);
}
Output:
January
February
March
April
May
June
July
August
September
October
November
December
Update: Do note that for different locales/cultures, the output might not be in English. Haven't tested that before though.
For US English only:
string[] monthNames = (new System.Globalization.CultureInfo("en-US")).DateTimeFormat.MonthNames;
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.