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

Find the Count of a Weekday Between Two Dates with LINQ

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
7 Apr 2012CPOL 22.6K   5   3
This is an alternative to using LINQ for "Find the count of a weekday between two dates without iterating/looping".

Introduction

Without going into a deep discussion of whether code or compiler is looping or not, it should be noted that LINQ can be very useful for tasks like this.

Further, if you add the methods using extension of DateTime, much flexibility is gained. This alternative demonstrates first how a range of weekdays can be created - offering you a collection of the actual dates - then, how to count the elements of the range which is the original goal of the tip.

Both methods are implemented with very little code which is easy to comprehend, maintain, and expand.

Using the Code

The code separates creation of the range of weekdays and the counting of these.

Using extensions allows for very tight code:

C#
DateTime currentDate = DateTime.Today;
DateTime anotherDate = currentDate.AddDays(23);
DayOfWeek thursday = DayOfWeek.Thursday;
Console.WriteLine(currentDate.WeekdayCount(anotherDate, thursday));
Console.ReadKey(); 

Code

C#
using System;
using System.Collections.Generic;
using System.Linq;                

namespace DateTimeExtension
{
    /// <summary>
    /// Extended methods for System.DateTime.
    /// </summary>
    public static class DateTimeExtensionMethods
    {
        /// <summary>        
        /// Returns the range of dates of the specified weekday
        /// between the current System.DateTime object and another date.
        /// </summary>
        /// <param name="currentDate">The current date</param>
        /// <param name="anotherDate">The other date of the interval to search</param>
        /// <param name="dayOfWeek">The weekday to find</param>
        /// <returns>The collection of dates of the specified weekday within the period.
        /// </returns>
        public static IEnumerable<DateTime> Weekdays(this DateTime currentDate, 
                      DateTime anotherDate, DayOfWeek dayOfWeek)
        {
            int sign = anotherDate.CompareTo(currentDate);
            return Enumerable.Range(0, sign * anotherDate.Subtract(currentDate).Days)
                .Select(delta => currentDate.AddDays(sign * (1 + delta)))
                .Where(date => date.DayOfWeek == dayOfWeek);
        }

        /// <summary>
        /// Returns the count of the specified weekday between
        /// the current System.DateTime object and another date.
        /// </summary>
        /// <param name="currentDate">The current date</param>
        /// <param name="anotherDate">The other date of the interval to search</param>
        /// <param name="dayOfWeek">The weekday to find</param>
        /// <returns>The count of the specified weekday within the period.</returns>
        public static int WeekdayCount(this DateTime currentDate, 
                          DateTime anotherDate, DayOfWeek dayOfWeek)
        {
            return currentDate.Weekdays(anotherDate, dayOfWeek).Count();
        }
    }
}

Usage is included as an in-line brief description.

History

  • 6th April, 2012: Initial version

License

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


Written By
Architect Cactus Data ApS
Denmark Denmark
Microsoft MVP, Most Valuable Professional, since 2017.

It started with BASIC in the 80s, then moved to PDC Prolog, and then - when Access 1.0 was launched - "back to Basic", or rather Access Basic. Then followed VBA (Visual Basic for Applications) starting with Microsoft Access 95/97 and still going with Access 2019/365.

Still I do some VBA, but since 2008 my main focus has been C#.

Application area is mainly accounting and custom applications related to accounting.

Comments and Discussions

 
QuestionMy take Pin
Jeff Lindholm9-Apr-12 4:37
Jeff Lindholm9-Apr-12 4:37 
AnswerDon't mix up "a weekday" and "weekdays" or workdays Pin
Gustav Brock9-Apr-12 10:01
professionalGustav Brock9-Apr-12 10:01 
Yep, many variations on this theme is possible.

But one can easily mix up weekday(s) and workdays. The original tip did not deal with workdays.

Also, I think one should be careful when including both dates in a count; this is not the case for most other calculations (the count of days between one date and the same date is usually considered zero) so at least - in my opinion - this should be optional.
NewsAn alternative using extensions without LINQ can be found here ... Pin
Gustav Brock7-Apr-12 10:37
professionalGustav Brock7-Apr-12 10:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.