这里有两种方法。
想法是生成范围内的每个日期,确定它是否是工作日,然后才将其添加到结果列表中。
GetBusinessDaysInRange 返回给定开始日期和结束日期之间的工作日日期列表。结束日期是唯一的,即如果结束日期是工作日,则它不会成为结果的一部分。
// Returns a list of the dates of the Business Days between the given start and end date
public static IEnumerable<DateTime> GetBusinessDaysInRange(DateTime startDate, DateTime endDate, DayOfWeek[] closedOn) {
if (endDate < startDate) {
throw new ArgumentException("endDate must be before startDate");
}
var businessDays = new List<DateTime>();
var date = startDate;
while (date < endDate) {
if (!closedOn.Contains(date.DayOfWeek)) {
businessDays.Add(date);
}
date = date.AddDays(1);
}
return businessDays;
}
GetFixedNumberOfBusinessDays 返回从给定开始到给定天数(您要求的方法)的工作日日期列表。
// Returns a list of the dates of the Business Days from the given start with the given number of days
public static IEnumerable<DateTime> GetFixedNumberOfBusinessDays(DateTime startDate, int numberOfBusinessDays, DayOfWeek[] closedOn) {
if (numberOfBusinessDays < 0) {
throw new ArgumentException("numberOfBusinessDays must be zero or positive.");
}
var businessDays = new List<DateTime>();
var date = startDate;
while (businessDays.Count() < numberOfBusinessDays) {
if (!closedOn.Contains(date.DayOfWeek)) {
businessDays.Add(date);
}
date = date.AddDays(1);
}
return businessDays;
}
引入参数DayOfWeek[] closedOn 是因为您不想硬编码一周中的非工作日。
返回类型改为IEnumerable<DateTime>,所以这个方法更通用。如果您只想要天数并且对实际日期不感兴趣,只需在结果上运行 .Count()。如果您想知道结束日期,请致电.Last()。
.Net Fiddle 使用示例:
var closedOn = new DayOfWeek[] { DayOfWeek.Saturday, DayOfWeek.Sunday };
var start = new DateTime(2018, 07, 23);
var numberOfDays = 10;
var businessDays = GetFixedNumberOfBusinessDays(end, numberOfDays, closedOn);
int actualNumberOfBusinessDays = businessDays.Count(); // 10
DateTime endDate = businessDays.Last(); // Friday, August 3, 2018