获取给定开始日期和结束日期之间的按月工作日

时间:2014-10-16 09:04:46

标签: c# asp.net datetime

我需要编写一个方法,我将传递开始日期和结束日期。输出应该是包含两个参数的列表。一个是月份名称,另一个是该月份的工作日。 (去除坐着和太阳)

请告知。

public List<MonthDaysData> GetMonthwiseWorkingdays(DateTime? start, DateTime? end)
{
List<MonthDaysData> monthdays = new List<MonthDaysData>();

// Coding to get the output
return monthdays;
}

public class MonthDaysData 
{ 
  public Int32? Month { get; set; } 
  public Int32? days { get; set; } 
} 

2 个答案:

答案 0 :(得分:0)

这听起来像是家庭作业,你不会显示你尝试过的东西,所以我不打算为你制作所有代码。这件事有quite some questions。有关返回工作日日期列表的简单实现,请参阅示例Get working days DateTime List of two dates

IEnumerable<DateTime> workingDays = WorkDaysBetween(DateTime start, DateTime end);

然后,您必须根据您的要求按月分组:

var groupedByMonth = workingDays.GroupBy(d => new DateTime(d.Year, d.Month, 1));

从那里你必须能够Select()正确的投射。

答案 1 :(得分:0)

您可以使用扩展方法来获取像这样的值......

public static class Extensions
{
    public static List<MonthDaysData> GetWorkingDaysPerMonthTo(this DateTime from, 
                         DateTime to)
    {
        var workings = new Dictionary<int, int>();
        var currentDateTime = from;

        while (currentDateTime <= to)
        {
            if (currentDateTime.DayOfWeek != DayOfWeek.Saturday 
                                  && currentDateTime.DayOfWeek != DayOfWeek.Sunday 
                                  && !currentDateTime.IsHoliday("CountryCode"))
                if (!workings.ContainsKey(currentDateTime.Month))
                    workings.Add(currentDateTime.Month, 1);
                else
                {
                    int curWork;
                    workings.TryGetValue(currentDateTime.Month, out curWork);
                    curWork++;
                    workings.Remove(currentDateTime.Month);
                    workings.Add(currentDateTime.Month, curWork);
                }

            currentDateTime = currentDateTime.AddDays(1);
        }
        return workings.Select(work => new MonthDaysData {Month = work.Key, 
                                                       days = work.Value}).ToList();
    } 

    public static bool IsHoliday(this DateTime date, string countryCode)
    {
        // some service that takes a country code and 
        // returns true/false if its a holiday
        return false;
    }
}

然后你可以从任何地方调用它......

var today = new DateTime(2014, 10, 16);
var dates = today.GetWorkingDaysPerMonthTo(new DateTime(2014, 12, 16));

然而,这只是平日工作日,你需要检查公众假期等。