c# - 如何计算工作 15 天并获得结束日期?
问题描述
用户入住酒店时如何计算我的实际工作日?我只想计算除周六和周日以外的工作日。请检查以下函数的计数工作日,但在参数中我输入了开始日期和结束日期。我只想发送开始日期,它会自动计算 15 个工作日并返回给我结束日期。//天数
public static double GetBusinessDays(DateTime startD, DateTime endD)
{
double calcBusinessDays =
1 + ((endD - startD).TotalDays * 5 -
(startD.DayOfWeek - endD.DayOfWeek) * 2) / 7;
if (endD.DayOfWeek == DayOfWeek.Saturday) calcBusinessDays--;
if (startD.DayOfWeek == DayOfWeek.Sunday) calcBusinessDays--;
return calcBusinessDays;
}
我想要这样:
public static Datetime GetBusinessDays(DateTime startDate)
{
Datetime After15WorkingDaysDate;
return After15WorkingDaysDate;
}
解决方案
这里有两种方法。
这个想法是生成范围内的每个日期,确定它是否是工作日,然后才将其添加到结果列表中。
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
推荐阅读
- macos - 如何在 macOS 中从 system_profiler 打印软件标题和安装日期?
- php - 服务提供者期间未调用授权门
- cassandra - Cassandra Schema Design - 处理相似但不同的源数据集的合并
- excel - 如何将图片从 Excel 复制并粘贴到 Word
- automated-tests - 有没有办法在 testcafe 中链接断言?
- c# - 表格重新加载数据时滑动取消(UITableView、UITableViewCell、UITableViewDelegate)
- php - 由于 laravel 命令,php artisan 迁移失败
- r - 如何计算循环数据的标准差
- python - Seaborn Barplot 和 Lineplot(共享 Y 轴)不能与其他图形的相同工作代码一起使用
- java - 如何比较Java中的字节打包字符串?