gpt4 book ai didi

C# 检查当前日期是该月的 1 日、2 日还是 3 日,忽略周末和附加 List

转载 作者:太空宇宙 更新时间:2023-11-03 21:18:40 25 4
gpt4 key购买 nike

我需要检查是否 DateTime.Now是在每个月的前 3 个工作日(周一至周五)。我还需要提供一个 List<DateTime>有国定假日,应相应处理。

如果 DateTime.Now 是星期六并且是该月的 1 号,则前 3 个工作日是星期一、星期二、星期三(该月的 3、4、5)。

    public bool IsBusinessDay()
{
DateTime now = DateTime.Now;

DateTime fbd = new DateTime();
DateTime sbd = new DateTime();
DateTime tbd = new DateTime();


DateTime fm = new DateTime(now.Year, now.Month, 1);
DateTime sm = new DateTime(now.Year, now.Month, 2);
DateTime tm = new DateTime(now.Year, now.Month, 3);

// first business day

if (fm.DayOfWeek == DayOfWeek.Sunday)
{
fbd = fm.AddDays(1);
}
else if (fm.DayOfWeek == DayOfWeek.Saturday)
{
fbd = fm.AddDays(2);
}
else
{
fbd = fm;
}

//second business day

if (sm.DayOfWeek == DayOfWeek.Sunday)
{
sbd = sm.AddDays(1);
}
else if (sm.DayOfWeek == DayOfWeek.Saturday)
{
sbd = sm.AddDays(2);
}
else
{
sbd = sm;
}

//third business day

if (tm.DayOfWeek == DayOfWeek.Sunday)
{
tbd = tm.AddDays(1);
}
else if (tm.DayOfWeek == DayOfWeek.Saturday)
{
tbd = tm.AddDays(2);
}
else
{
tbd = tm;
}

if (now == fdb || now == sbd || now == tbd)
{
return true;
}

return false;
}

这是一个好方法吗?如何添加 List<DateTime> with holidays 并检查当前日期是否不是假期?

我有一种感觉,我想多了,而且想得不好。我不知道为什么,但同样的感觉告诉我有更简单的方法。

最佳答案

这应该做你想做的。您必须提供一组假期。

public static bool IsFirstThreeBusinessDays(DateTime date, HashSet<DateTime> holidays)
{
DateTime dt = new DateTime(date.Year, date.Month, 1);
int businessDaysSeen = 0;

while (businessDaysSeen < 3)
{
if (dt.DayOfWeek != DayOfWeek.Saturday &&
dt.DayOfWeek != DayOfWeek.Sunday &&
!holidays.Contains(dt))
{
if (dt == date.Date)
{
return true;
}

businessDaysSeen++;
}

dt = dt.AddDays(1);
}

return false;
}

关于C# 检查当前日期是该月的 1 日、2 日还是 3 日,忽略周末和附加 List<DateTime>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32318405/

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