获取一个月的星期六

时间:2018-08-08 16:41:21

标签: c#

我正在尝试获取每个月的星期六的天数。

例如,本月(八月)应返回:4,11,18,28

int year = 2018;
int month = DateTime.Now.Month;
DateTime myDT = new DateTime(year, month, 1, new GregorianCalendar());
Calendar myCal = CultureInfo.InvariantCulture.Calendar;

while (myDT.Month == month)
{
    var day = myCal.GetDayOfWeek(myDT);

    if (day == DayOfWeek.Saturday || day == DayOfWeek.Friday)
        Debug.WriteLine(myCal.GetDayOfMonth(myDT));

    myDT.AddDays(1);
}

一旦我单击执行代码的按钮,我的UI将被冻结,而不会返回任何错误。这使我相信由于某种原因它仍然在循环中。

1 个答案:

答案 0 :(得分:2)

尝试一下:

    const int year = 2018;
    int month = DateTime.Now.Month;

    Calendar myCal = CultureInfo.InvariantCulture.Calendar;
    DayOfWeek[] accepted = new [] { DayOfWeek.Saturday, DayOfWeek.Friday };

    IEnumerable<DateTime> dateTimes = Enumerable.Range(1, DateTime.DaysInMonth(year, month)) 
        .Select(day => new DateTime(year, month, day))
        .Where(d => accepted.Contains(myCal.GetDayOfWeek(d)));