views:

116

answers:

3

Hello,

I can't get this method to return the right date. What this method does is take the current date and add the amount of days you specify. So if you want the next Monday, it'll return the next Monday. It also sends the date into a method that checks to see if it's one of the "Filtered Dates" that aren't allowed to be returned. This all works fine except for the recursion. What I wanted to do is if a date is a "filtered date" run the same method again, adding days until it reaches an unfiltered date. What happens though is say I pass in 10/12/2009 and this is a filtered date, it does the recursion, adds the days and returns 10/19/2009 but then it looks like it returns again but returning 10/12/2009. What am I doing wrong? thanks

private static DateTime Next(DateTime current, DayOfWeek dayOfWeek, int weeksAhead)
{
    int offsetDays = dayOfWeek - current.DayOfWeek;
    if (offsetDays <= 0)
    {
        offsetDays += 7 * weeksAhead;
    }
    DateTime result = current.AddDays(offsetDays);
    //MAKE SURE RESULT IS NOT A FILTERED DATE
    if (IsFiltered(result))
    {
        Next(result, dayOfWeek, 1);

    }
    //IF IT IS, RUN NEXT AGAIN WITH AN INCREMENTAL WEEK
    return result;
}
+8  A: 

Replace

Next(result, dayOfWeek, 1);

with

return Next(result, dayOfWeek, 1);

You are not returning (nor storing) the result of the recursive call.

Jason
A: 

You aren't returning the result within your if(IsFiltered(result)) statement. Change it to:

if (IsFiltered(result))
{
    return Next(result, dayOfWeek, 1);
}
else
{
    return result;
}
Scott Ferguson
A: 

private static DateTime Next(DateTime current, DayOfWeek dayOfWeek, int weeksAhead)
{
    current = current
        .AddDays((current.DayOfWeek - dayOfWeek) * -1)
        .AddDays(7 * weeksAhead);

    // recursive approach
    if (IsFiltered(current))
    {
        return Next(current, dayOfWeek, 1);
    }
    else
    {
        return current;
    }

    // I prefer this approach, without recursion
    while(IsFiltered(current))
        current = Next(current, dayOfWeek, 1);
    return current;
}
Rubens Farias