生成两个日期之间的每周营业日期列表,不包括周末和节假日

时间:2019-02-22 19:54:59

标签: c#

我想生成两个日期之间的每周营业日期列表,不包括周末和节假日。我设法排除了周末,并为假期创建了例程。现在,我需要排除假期。下面是我的代码。

using System;
using System.Collections.Generic;
using System.Linq;

namespace SeriesTest
{
    class Program
    {
        public class BusinessWeekDays
        {
            public DateTime Monday;
            public DateTime Sunday;
        }

        private static List<DateTime> Holidays = new List<DateTime>()
        {
            new DateTime(1, 1, 1), //New Year Day
            new DateTime(1, 5, 1), //Labour Day
            new DateTime(1, 7, 4), //Independence Day
            new DateTime(1, 3, 1), //Martin Luther King Jr. Day
            new DateTime(1, 3, 2), //Presidents Day 
            new DateTime(1, 12, 25), //Christmas
            new DateTime(1, 5, 5), //Memorial Day
            new DateTime(1, 9, 1), //Labor Day
            new DateTime(1, 10, 2), //Columbus Day
            new DateTime(1, 11, 4), //Columbus Day
        };

    private static bool IsHoliday(DateTime value, List<DateTime> holidays = null)
    {
        if (null == holidays)
            holidays = Holidays;

        return (value.DayOfWeek == DayOfWeek.Sunday) ||
               (value.DayOfWeek == DayOfWeek.Saturday) ||
               holidays.Any(holiday => holiday.Day == value.Day &&
                                       holiday.Month == value.Month);
    }

    public static int BusinessDays(DateTime fromDate, DateTime toDate, List<DateTime> holidays = null)
    {
        int result = 0;
        for (var date = fromDate;
            date < toDate.Date;
            date = date.AddDays(1))
            if (!IsHoliday(date, holidays))
                result += 1;

        return result;
    }

    static void Main(string[] args)
    {


        var StartDate = DateTime.Parse("02/12/2019");
        var SeriesEndDate = DateTime.Parse("12/31/2025");
        var holidays = new List<DateTime>();

        var firstMonday = Enumerable.Range(0, 7)
            .SkipWhile(x => StartDate.AddDays(x).DayOfWeek != DayOfWeek.Monday)
            .Select(x => StartDate.AddDays(x))
            .First();

        var ts = (SeriesEndDate - firstMonday);

        var dates = new List<BusinessWeekDays>();

        for (var i = 0; i < ts.Days; i += 7)
        {

            //Remove holidays. Weekend already removed here
            if (BusinessDays(StartDate, SeriesEndDate, holidays) != 0)
            {

                dates.Add(new BusinessWeekDays { Monday = firstMonday.AddDays(i), Sunday = firstMonday.AddDays(i + 9) });
            }

        }

        Console.WriteLine(dates);

        }


    }
}

1 个答案:

答案 0 :(得分:0)

您似乎已经拥有了所需的一切,但是holidays从未设置为Holidays。更改下面的行,以便将holidays设置为null。然后它将打入IsHoliday中的空检查并正确设置。

var holidays = new List<DateTime>();

应该是:

var holidays = null;