Home > Mobile >  Get next given day after a month in c#
Get next given day after a month in c#

Time:11-18

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

CodePudding user response:

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, when after adding 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);

CodePudding user response:

Add a month, instead of a week to the start date:

public static DateTime GetSameDayAfterMonth(DateTime start)
{
    var compare = start.AddMonths(1);
    // The % 7 ensures we end up with a value in the range [0, 6]
    int daysToAdd = ((int)start.DayOfWeek - (int)compare.DayOfWeek) % 7;
    return compare.AddDays(daysToAdd);
}

Example:

var dayInNextMonth = GetSameDayAfterMonth(DateTime.Parse("2021-11-17")); // 2021-12-15

var weekday = dayInNextMonth.DayOfWeek; // Wednesday
  • Related