Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get next given day after a month in c#

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);
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Typical month has 30 or 31 days, however, the next same day of week will be after either 28 (4 * 7) or 35 (5 * 7) days. We need a compromise. Let for February add 28 days and for all the other months add 35 days:

public static DateTime GetSameDayAfterMonth(DateTime start) =>
  start.AddDays((start.AddMonths(1) - start).TotalDays < 30 ? 28 : 35);

Sure, you can elaborate other rules: say, if when add 28 days we are still in the same month (1 May + 28 days == 29 May) we should add 35:

public static DateTime GetSameDayAfterMonth(DateTime start) =>
  start.AddDays(start.Month == start.AddDays(28).Month ? 35 : 28);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading