How to list all month names, e.g. for a combo?

后端 未结 16 931
栀梦
栀梦 2020-12-23 14:38

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?

相关标签:
16条回答
  • 2020-12-23 14:49

    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);
    
    0 讨论(0)
  • 2020-12-23 14:50

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

    System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
    
    0 讨论(0)
  • 2020-12-23 14:50

    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));
    
    0 讨论(0)
  • 2020-12-23 14:54
    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;
    
    0 讨论(0)
  • 2020-12-23 14:57

    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.

    0 讨论(0)
  • 2020-12-23 14:59

    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).

    0 讨论(0)
提交回复
热议问题