SkyeBoniwell
SkyeBoniwell

Reputation: 7092

getting the date of monday and friday from next week

I have the following method that I use to get the date for Monday and Friday of next week.

For example, today is 1/6/2017. If I ran it, I would hope to get the following results:

monday = 1/9/2017
friday = 1/13/2017

The method works fine if I run it earlier in the week, but if I run it later like a friday or saturday, it returns the monday and friday dates 2 weeks from now(not next week).

For example, running it today(Friday the 6th), I get the following results:

monday = 1/16/2017
friday = 1/20/2017

Here is the method:

public static DateTime NextWeekRange(DateTime start, DayOfWeek day)
{
    var add_days = ((int)day - (int)start.DayOfWeek + 7) % 7;
    return start.AddDays(add_days);
}

And I call it like this:

var monday = NextWeekRange(DateTime.Today.AddDays(i_today), DayOfWeek.Monday);
var friday = NextWeekRange(DateTime.Today.AddDays(i_today + 4), DayOfWeek.Friday);

I'm not quite sure what I got wrong, so another pair of eyes would help!

Thanks!

Upvotes: 0

Views: 123

Answers (1)

M.Othman
M.Othman

Reputation: 40

DateTime MyDate = DateTime.Now;
        DateTime NextMondayDate;
        DateTime NextFridayDate;
        Boolean Test = true;
        while (Test)
        {
            if (MyDate.DayOfWeek.ToString().ToUpper() == "MONDAY")
            {
                NextMondayDate = MyDate;
                NextFridayDate = MyDate.AddDays(4);
                Test = false;
            }

            else if (MyDate.DayOfWeek.ToString().ToUpper() == "FRIDAY")
            {
                NextFridayDate = MyDate;
                NextMondayDate = MyDate.AddDays(3);
                Test = false;
            }
            else
            {
                MyDate = MyDate.AddDays(1);
            } 

        }

Upvotes: 0

Related Questions