After many, many edits, corrections and re-writes, here is my final answer:
The method that follows returns a a DateTime
representing the next time the day of number day
comes up in the calendar. It does so using an iterative approach, and is written in the form of an extension method for DateTime
objects, and thus isn't bound to today's date but will work with any date.
The code executes the following steps to get the desired result:
- Ensure that the day number provided is valid (greater than zero and smaller than 32).
- Enter into a while loop that keeps going forever (until we break).
- Check if
cDate
's month works (the day must not have passed, and the month must have enough days in it).
- If so, return.
- If not, increase the month by one, set the day to one, set
includeToday
to true so that the first day of the new month is included, and execute the loop again.
The code:
static DateTime GetNextDate3(this DateTime cDate, int day, bool includeToday = false)
{
if (day > 0 && day <= 31)
{
while (true)
{
if ((includeToday && day > cDate.Day || (includeToday && day >= cDate.Day)) && day <= DateTime.DaysInMonth(cDate.Year, cDate.Month))
{
break;
}
cDate = cDate.AddDays(1 - cDate.Day).AddMonths(1);
includeToday = true;
}
return new DateTime(cDate.Year, cDate.Month, day);
}
throw new ArgumentOutOfRangeException("day", "Day isn't valid");
}