在给定的开始日期和结束日期之间按月计算工作日
本文关键字:日期 之间 工作日 计算 结束 开始 | 更新日期: 2023-09-27 18:26:53
我需要编写一个方法,在该方法中我将传递开始日期和结束日期。输出应该是一个包含两个参数的列表。一个是月份名称,另一个是该月份的工作日编号。(移除sat和sun)
请告知。
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; }
}
您可以使用扩展方法来获得这样的值。。。
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));
然而,这只是将工作日作为工作日,您需要查看公共假日等。
这听起来像是家庭作业,而且你没有展示你已经尝试过的内容,所以我不会为你大量编写所有代码。关于这件事有许多问题。例如,请参阅Get working days DateTime两个日期的列表,以获得返回工作日日期列表的简单实现:
IEnumerable<DateTime> workingDays = WorkDaysBetween(DateTime start, DateTime end);
然后,您必须根据您的要求按月对其进行分组:
var groupedByMonth = workingDays.GroupBy(d => new DateTime(d.Year, d.Month, 1));
从那里你必须能够Select()
正确的投影。