Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Find the count of a weekday between two dates without iterating/looping

0.00/5 (No votes)
23 Nov 2011CPOL 4.8K  
Didn't read it very closely, haven't tested it very thoroughly, but, you get the idea:public int GetNumberOfRecurrances(DayOfWeek weekDay, DateTime startDate, DateTime endDate){ int distanceToFirstInstance = ((int)weekDay - ((int)startDate.DayOfWeek)); //determine integer...
Didn't read it very closely, haven't tested it very thoroughly, but, you get the idea:

C#
public int GetNumberOfRecurrances(DayOfWeek weekDay, DateTime startDate, DateTime endDate)
{
    int distanceToFirstInstance = ((int)weekDay - ((int)startDate.DayOfWeek));

    //determine integer number of days with left
    int range = ((int)((endDate.ToUniversalTime().Ticks / 10000000) - (startDate.ToUniversalTime().Ticks / 10000000))) / 86400;

    return ((int)distanceToFirstInstance >= 0
        ? (int)((Math.Floor((decimal)(range - distanceToFirstInstance) / 7)) + 1)
        : (int)((Math.Floor((decimal)(range - (distanceToFirstInstance + 7)) / 7)+1)));
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)