gpt4 book ai didi

c# - AddBusinessDays 和 GetBusinessDays

转载 作者:IT王子 更新时间:2023-10-29 03:38:19 24 4
gpt4 key购买 nike

我需要找到 2 个优雅的完整实现

public static DateTime AddBusinessDays(this DateTime date, int days)
{
// code here
}

and

public static int GetBusinessDays(this DateTime start, DateTime end)
{
// code here
}

O(1) 更可取(无循环)。

编辑: 工作日是指工作日(星期一、星期二、星期三、星期四、星期五)。没有假期,只有周末除外。

我已经有了一些看起来可行的丑陋解决方案,但我想知道是否有优雅的方法可以做到这一点。谢谢


这是我到目前为止所写的内容。它适用于所有情况,也有负面影响。仍然需要 GetBusinessDays 实现

public static DateTime AddBusinessDays(this DateTime startDate,
int businessDays)
{
int direction = Math.Sign(businessDays);
if(direction == 1)
{
if(startDate.DayOfWeek == DayOfWeek.Saturday)
{
startDate = startDate.AddDays(2);
businessDays = businessDays - 1;
}
else if(startDate.DayOfWeek == DayOfWeek.Sunday)
{
startDate = startDate.AddDays(1);
businessDays = businessDays - 1;
}
}
else
{
if(startDate.DayOfWeek == DayOfWeek.Saturday)
{
startDate = startDate.AddDays(-1);
businessDays = businessDays + 1;
}
else if(startDate.DayOfWeek == DayOfWeek.Sunday)
{
startDate = startDate.AddDays(-2);
businessDays = businessDays + 1;
}
}

int initialDayOfWeek = (int)startDate.DayOfWeek;

int weeksBase = Math.Abs(businessDays / 5);
int addDays = Math.Abs(businessDays % 5);

if((direction == 1 && addDays + initialDayOfWeek > 5) ||
(direction == -1 && addDays >= initialDayOfWeek))
{
addDays += 2;
}

int totalDays = (weeksBase * 7) + addDays;
return startDate.AddDays(totalDays * direction);
}

最佳答案

第一个功能的最新尝试:

public static DateTime AddBusinessDays(DateTime date, int days)
{
if (days < 0)
{
throw new ArgumentException("days cannot be negative", "days");
}

if (days == 0) return date;

if (date.DayOfWeek == DayOfWeek.Saturday)
{
date = date.AddDays(2);
days -= 1;
}
else if (date.DayOfWeek == DayOfWeek.Sunday)
{
date = date.AddDays(1);
days -= 1;
}

date = date.AddDays(days / 5 * 7);
int extraDays = days % 5;

if ((int)date.DayOfWeek + extraDays > 5)
{
extraDays += 2;
}

return date.AddDays(extraDays);

}

第二个函数 GetBusinessDays 可以按如下方式实现:

public static int GetBusinessDays(DateTime start, DateTime end)
{
if (start.DayOfWeek == DayOfWeek.Saturday)
{
start = start.AddDays(2);
}
else if (start.DayOfWeek == DayOfWeek.Sunday)
{
start = start.AddDays(1);
}

if (end.DayOfWeek == DayOfWeek.Saturday)
{
end = end.AddDays(-1);
}
else if (end.DayOfWeek == DayOfWeek.Sunday)
{
end = end.AddDays(-2);
}

int diff = (int)end.Subtract(start).TotalDays;

int result = diff / 7 * 5 + diff % 7;

if (end.DayOfWeek < start.DayOfWeek)
{
return result - 2;
}
else{
return result;
}
}

关于c# - AddBusinessDays 和 GetBusinessDays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1044688/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com