Get list of months from <DateTime>

I use List in ASP.NET 3.5 / C # to filter an existing list of dates (about 20 in total) in a specific month. Therefore, if the user selects the year 2010 (ddlFromYear.SelectedItem.Text == 2010), then the returned list will consist of only 8 months, because we go only to August.

My question is: how can I output DateTime as int, or even better than a month? "August". Thus, when I link another DropDown, I can list all the months (January, February ...), which, as I mentioned, will be determined by years (2009, 2010 ...)

    int yearSelected;
    bool success = Int32.TryParse(ddlFromYear.SelectedItem.Text, out yearSelected);
    if (success)
    {
        List<DateTime> datesSelected = new List<DateTime>();
        datesSelected =
            (from n in dates
             where n.Year.Equals(yearSelected)
             select n).ToList();

        dateMonths.Sort();
        ddlFromMonth.Items.Clear();
        ddlFromMonth.DataSource = datesSelected;
        ddlFromMonth.DataBind();
    }
+3
source share
2 answers

, , -

List<string> months = (from n in dates 
                      where n.Year.Equals(yearSelected)
                      select n.ToString("MMM")).ToList();

// optionally include call to .Distinct() prior to .ToList() if there 
// could be duplicates and you want to exclude them

{ "January", "February", "March" /* etc. */ };

+6

. , (.. ), :

DateTimeFormatInfo formatInfo = CultureInfo.CurrentCulture.DateTimeFormat;
List<string> month = dates.Select(n => n.Month)
                          .Distinct()
                          .OrderBy(n => n)
                          .Select(n => formatInfo.GetMonthName(n))
                          .ToList();
0

Source: https://habr.com/ru/post/1760790/


All Articles