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?
I did in the following way: (it's possible to set the culture)
var months = Enumerable.Range(1, 12).Select(i =>
new
{
Index = i,
MonthName = new CultureInfo("en-US").DateTimeFormat.GetAbbreviatedMonthName(i)
})
.ToDictionary(x => x.Index, x => x.MonthName);
You can use the following to return an array of string containing the month names
System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
You can easily do something like below with linq so that you only have 12 items in your drop down.
var Months = new SelectList((DateTimeFormatInfo.CurrentInfo.MonthNames).Take(12));
List<string> mnt = new List<string>();
int monthCount = Convert.ToInt32(cbYear.Text) == DateTime.Now.Year ? DateTime.Now.Month : 12;
for (int i = 0; i < monthCount; i++)
{
mnt.Add(CultureInfo.CurrentUICulture.DateTimeFormat.MonthNames[i]);
}
cbMonth.DataSource = mnt;
A way to retrieve a dynamic culture specific list of month names in C# with LINQ.
ComboBoxName.ItemsSource=
System.Globalization.CultureInfo.
CurrentCulture.DateTimeFormat.MonthNames.
TakeWhile(m => m != String.Empty).ToList();
OR
In this example an anonymous object is created with a Month and MonthName property
var months = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
.TakeWhile(m => m != String.Empty)
.Select((m,i) => new
{
Month = i+1,
MonthName = m
})
.ToList();
PS: We use the method TakeWhile because the MonthNames array contains a empty 13th month.
You can use the DateTimeFormatInfo to get that information:
// Will return January
string name = DateTimeFormatInfo.CurrentInfo.GetMonthName(1);
or to get all names:
string[] names = DateTimeFormatInfo.CurrentInfo.MonthNames;
You can also instantiate a new DateTimeFormatInfo
based on a CultureInfo
with DateTimeFormatInfo.GetInstance or you can use the current culture's CultureInfo.DateTimeFormat property.
var dateFormatInfo = CultureInfo.GetCultureInfo("en-GB").DateTimeFormat;
Keep in mind that calendars in .Net support up to 13 months, thus you will get an extra empty string at the end for calendars with only 12 months (such as those found in en-US or fr for example).