Get last/next week Wednesday date in C#

To find the next Wednesday just keep adding days until you find one. To find the previous Wednesday just keep subtracting days until you get to one.

DateTime nextWednesday = DateTime.Now.AddDays(1);
while (nextWednesday.DayOfWeek != DayOfWeek.Wednesday)
    nextWednesday = nextWednesday.AddDays(1);
DateTime lastWednesday = DateTime.Now.AddDays(-1);
while (lastWednesday.DayOfWeek != DayOfWeek.Wednesday)
    lastWednesday = lastWednesday.AddDays(-1);

Use the AddDays routine:

        // increment by the number of offset days to get the correct date
        DayOfWeek desiredDay = DayOfWeek.Wednesday;
        int offsetAmount = (int) desiredDay - (int) DateTime.Now.DayOfWeek;
        DateTime lastWeekWednesday = DateTime.Now.AddDays(-7 + offsetAmount);
        DateTime nextWeekWednesday = DateTime.Now.AddDays(7 + offsetAmount);

That should do it!

NOTE: If it is a Monday, "Last Wednesday" is going to give you the very last Wednesday that occurred, but "Next Wednesday" is going to give you the Wednesday 9 days from now! If you wanted to get the Wednesday in two days instead you would need to use the "%" operator. That means the second "nextweek" statement would read "(7 + offsetAmount) % 7".


DateTime.Now.AddDays(7) and DateTime.Now.AddDays(-7) is how you can do arithmetic, assuming you are on Wednesday. If you aren't, what you would need to do is use the DayOfWeek property to determine the number of days (positive and negative) that you would need to determine which day is 'Wednesday'. Then you can pass that value into AddDays.

For instance, if today was tuesday, you would AddDays(-6) for last Wednesday and AddDays(8) for next Wednesday.

I'll leave you the task of calculating those.

Tags:

C#