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

后端 未结 16 933
栀梦
栀梦 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 15:12
    public IEnumerable<SelectListItem> Months
    {
      get
      {
        return Enumerable.Range(1, 12).Select(x => new SelectListItem
        {
          Value = x.ToString(),
          Text = DateTimeFormatInfo.CurrentInfo.GetMonthName(x)
        });
      }
    }
    
    0 讨论(0)
  • 2020-12-23 15:14

    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!

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

    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.

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