我需要检查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>
并检查当前日期不是假日?
我有一种感觉,我在思考这个,并以一种糟糕的方式思考它。我不知道为什么,但同样的感觉告诉我有一种更容易的方法。
答案 0 :(得分:3)
这应该做你想要的。你必须提供一套假期。
Phoenix.Socket.assign/3
答案 1 :(得分:1)
您也可以使用LINQ执行此操作。
public static bool IsFirstThreeBusinessDays(DateTime date, HashSet<DateTime> holidays)
{
var query =
Enumerable.Range(1, DateTime.DaysInMonth(date.Year, date.Month))
.Select(o => new DateTime(date.Year, date.Month, o))
.Where(o => o.DayOfWeek != DayOfWeek.Saturday && o.DayOfWeek != DayOfWeek.Sunday
&& !holidays.Contains(o))
.Take(3);
return query.Contains(date);
}
答案 2 :(得分:0)
以下是:
public static IEnumerable<DateTime> BusinessDaysOfMonth(DateTime time)
{
var month = new DateTime(time.Year, time.Month, 1);
var nextMonth = month.AddMonths(1);
var current = month;
while(current < nextMonth)
{
if (IsWeekday(current) && !IsHoliday(current))
{
yield return current;
}
current = current.AddDays(1);
}
}
(请注意,某些方法取自下方)。然后,您需要使用的所有内容是:
// Get first three business days
var firstThreeBizDays = BusinessDaysOfMonth(DateTime.Now).Take(3);
// Check if today is one of them
var result = firstThreeBizDays.Contains(DateTime.Today);
老答案:
好的,所以看起来你需要确保三个条件。他们是:
这可以直接转换为代码:
public static bool IsFirstThreeDays(DateTime time) => time.Day < 4;
public static bool IsWeekday(DateTime time)
{
var dow = time.DayOfWeek;
return dow != DayOfWeek.Saturday && dow != DayOfWeek.Sunday;
}
public bool IsHoliday(DateTime time)
{
ISet<DateTime> holidays = ??; // Decide whether this is a member or an arg
return holidays.Contains(time.Date);
}
请注意,holidays
集需要包含每个假日中任何Day
的{{1}}个组件。
现在你的方法可能只是:
DateTime