Counts the number of weekends between two dates. - CSharp System

CSharp examples for System:DateTime Week

Description

Counts the number of weekends between two dates.

Demo Code

//   The contents of this file are subject to the New BSD
using System;/*ww w.java2s.  c o m*/

public class Main{
        /// <summary>
    /// Counts the number of weekends between two dates.
    /// </summary>
    /// <param name="startTime">The start time.</param>
    /// <param name="endTime">The end time.</param>
    /// <returns></returns>
    public static int CountWeekends(this DateTime startTime, DateTime endTime) {
        TimeSpan ts = endTime - startTime;
        Console.WriteLine(ts.Days);
        int cnt = 0;
        for (int i = 0; i < ts.Days; i++) {
            DateTime dt = startTime.AddDays(i);
            if (IsWeekEnd(dt))
                cnt++;
        }
        return cnt;
    }
        /// <summary>
    /// Checks to see if the date is a week day (Mon - Fri)
    /// </summary>
    /// <param name="dt">The dt.</param>
    /// <returns>
    /// 	<c>true</c> if [is week day] [the specified dt]; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsWeekDay(this DateTime dt) {
        return (dt.DayOfWeek != DayOfWeek.Saturday && dt.DayOfWeek != DayOfWeek.Sunday);
    }
}

Related Tutorials