我正面临的有趣问题,我无法想出一个计算算法。
基本上,我想要的是根据DateTime.Now.AddMinutes()计算DateTime,但添加分钟应该考虑工作时间和周末。
换句话说,如果时间当前是16:50并且我加了20分钟,那么该方法应该在明天早上08:10返回DateTime(如果明天不是周末那天)。
我从一些逻辑开始,但它并不完整。有没有人有一个样本可以节省我几个小时的编码?这是我到目前为止所得到的:
public DateTime CalculateSLAFromNow(int minutes)
{
DateTime now = DateTime.Now;
TimeSpan slatimeaddedon = CalculateToNextWeekDay(DateTime.Now);
TimeSpan finalMinutesAddedon = slatimeaddedon.Add(new TimeSpan(0, minutes, 0));
DateTime SLATime = DateTime.Now.AddMinutes(slatimeaddedon.TotalMinutes);
return SLATime;
}
private TimeSpan CalculateToNextWeekDay(DateTime dt)
{
//Calculate.
}
答案 0 :(得分:1)
public static DateTime CalculateSLAFromNow(int minutes)
{
double days = (double)minutes / 540;
DateTime now = DateTime.Now;
DateTime later = now;
while (days >= 1)
{
later = later.AddDays(1);
if (later.DayOfWeek == DayOfWeek.Saturday)
{
later = later.AddDays(2);
}
days--;
}
days = days * 540;
later = later.AddMinutes(days);
if (later.Hour > 17)
{
later = later.AddHours(15);
}
if (later.DayOfWeek == DayOfWeek.Saturday)
{
later = later.AddDays(2);
}
else if(later.DayOfWeek == DayOfWeek.Sunday)
{
later = later.AddDays(1);
}
return later;
}
现在它可以添加任意分钟数(不是最漂亮的代码,但它有效)