Reputation: 211
I'm trying to get the day number of Saturdays of each month.
For example, this month (August) should return: 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);
}
Once I click the button that executes the code, my UI is frozen with no errors returned. This leads me to believe it's still inside the loop for some reason.
Upvotes: 2
Views: 294
Reputation: 859
Try this:
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)));
Upvotes: 2
Reputation: 4883
You are not assigning it so it maybe be in an eternal loop:
Instead of this:
myDT.AddDays(1);
Do this:
myDT = myDT.AddDays(1);
Upvotes: 2