【发布时间】:2019-02-21 08:58:13
【问题描述】:
我正在搜索 stackoverflow 以找到完全匹配的问题和类似问题的响应,以便在 C# 中解决。
虽然我在可用问题上发现了一些相似之处,但我找不到任何关于如何在 c# 中以天、小时和分钟计算 SLA 的特定问题和回应,不包括公共假期、周末和非工作时间。
例如,我将工单提出的日期时间设置为 21/02/2019 10:00:00 pm,如果我只想添加 n(在本例中为 21)工作小时数,不包括非工作时间,在 C# 中查找该票的 sla 日期时间。
虽然我在仅计算工作时间、周末时实施了一些逻辑,但发现很难排除公共假期。也欣赏比长行函数更好、简单和易于理解的方法(可能使用 linq)。感谢社区提供的任何示例代码。
我从下面的其他 stackoverflow 链接中得到了一个工作解决方案,但这需要更多的改进来简化和解决任何可能的错误,例如如果我们连续放 2 天假期,则无法处理这种情况,然后计算 sla从第 3 天开始,等等。
目前我得到的解决方案是:
public virtual DateTime AddWithinWorkingHours(DateTime start, TimeSpan offset)
{
//Get publicholidaysList from holiday table to not to include in working hour calculation
var holidaysList = _holidayManager.GetHolidays().Result;
// Don't start counting hours until start time is during working hours
if (start.TimeOfDay.TotalHours > StartHour + HoursPerDay)
start = start.Date.AddDays(1).AddHours(StartHour);
if (start.TimeOfDay.TotalHours < StartHour)
start = start.Date.AddHours(StartHour);
if (start.DayOfWeek == DayOfWeek.Saturday)
start.AddDays(2);
//if it is a Sunday or holiday date, skip that date in workinghour calc
else if (start.DayOfWeek == DayOfWeek.Sunday || holidaysList.Exists(hd=>hd.Date == start.Date))
start.AddDays(1);
// Calculate how much working time already passed on the first day
TimeSpan firstDayOffset = start.TimeOfDay.Subtract(TimeSpan.FromHours(StartHour));
// Calculate number of whole days to add
int wholeDays = (int)(offset.Add(firstDayOffset).TotalHours / HoursPerDay);
// How many hours off the specified offset does this many whole days consume?
TimeSpan wholeDaysHours = TimeSpan.FromHours(wholeDays * HoursPerDay);
// Calculate the final time of day based on the number of whole days spanned and the specified offset
TimeSpan remainder = offset - wholeDaysHours;
// How far into the week is the starting date?
int weekOffset = ((int)(start.DayOfWeek + 7) - (int)DayOfWeek.Monday) % 7;
// How many weekends are spanned?
int weekends = (int)((wholeDays + weekOffset) / 5);
// Calculate the final result using all the above calculated values
return start.AddDays(wholeDays + weekends * 2).Add(remainder);
}
【问题讨论】:
-
您有公共假期的数据源吗?
-
是的。我几乎没有选择,即带有用户输入的假日日期和描述的假日表。选项 2 是从特定于国家/地区的公共假日 api 接收假日 json 并将其存储在我们的系统中以计算此逻辑。具体来说,基本假期表将像 Id、日期、名称。
-
我不明白为什么有些人反对这个问题?那些人可以留下一些关于为什么不投票的问题会很好。谢谢
-
可能是因为您提出了如此广泛的问题,其中涉及更详细的答案,并且通过展示您尝试实施的示例以及您实际遇到的问题来表明您没有努力解决问题。其次,人们实际上给了你 2 个解决你的问题的方法,你甚至都懒得去研究它
-
@Tiago,事实上我已经有了相同的解决方案,因为它更接近我的问题,但这并没有排除假期,还通过重构寻找任何优雅的解决方案。因此,我已经尽我所能编辑了我的问题,并接受了您的努力作为答案,并将其与我的业务逻辑和单元测试相结合。顺便说一句,我不同意这个问题如此广泛,需要更详细的答案。我正在寻找的只是一些基本的逻辑/伪代码也可以。确保考虑更好的方法。