Click here to Skip to main content
15,885,767 members
Articles / Web Development / ASP.NET
Alternative
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
23 Nov 2011CPOL 4.7K  
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)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --