简体   繁体   中英

Recursion and return Dates in C#

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

Replace

Next(result, dayOfWeek, 1);

with

return Next(result, dayOfWeek, 1);

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM