2 回答
TA贡献1794条经验 获得超7个赞
它应该是泛型方法。您可以在其他地方添加不同的工作日。
public static DateTime AddWorkdays(this DateTime originalDate, int workDays)
{
DateTime tmpDate = originalDate;
while (workDays > 0)
{
tmpDate = tmpDate.AddDays(1);
if (tmpDate.DayOfWeek == DayOfWeek.Saturday ||
tmpDate.DayOfWeek == DayOfWeek.Sunday )
workDays--;
}
return tmpDate;
}
DateTime endDate = startDate.AddWorkdays(15);
TA贡献2080条经验 获得超4个赞
这里有两种方法。
这个想法是生成范围内的每个日期,决定它是否是工作日,然后才将其添加到结果列表中。
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()对结果运行 a 。如果您想要结束日期,请致电.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
- 2 回答
- 0 关注
- 164 浏览
添加回答
举报