我正在尝试获取每个月的星期六的天数。
例如,本月(八月)应返回: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将被冻结,而不会返回任何错误。这使我相信由于某种原因它仍然在循环中。
答案 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)));