How can I get the next particular day after a month in c#,
for example if today is Monday
I need to get the first Monday
after 1 month from now, but in more generic way, for example if today is 17/11/2021
which is Wednesday
I need to get the first Wednesday
after a month from now.
I am using this function but it will return for next week and not next month:
public static DateTime GetNextWeekday(DateTime start, DayOfWeek day)
{
// The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
int daysToAdd = ((int)day - (int)start.DayOfWeek + 7) % 7;
return start.AddDays(daysToAdd);
}
2
Answers
Add a month, instead of a week to the start date:
Example:
Typical month has
30
or31
days, however, the next same day of week will be after either28
(4 * 7
) or35
(5 * 7
) days. We need a compromise. Let forFebruary
add28
days and for all the other months add35
days:Sure, you can elaborate other rules: say, when after adding
28
days we are still in the same month (1 May + 28 days == 29 May
) we should add35
: