问题描述
我有一个需要在日期字段上工作的要求,所以要求是这样的东西
I have a requirement where I need to work on a date field, so the requirement is some thing like this
我将字段称为 minimum可能的日期
-
为日期添加+1
Add +1 to the date
如果最短的日期恰好是添加1天后的周末(星期六或星期日),请显示下一个工作日,即星期一
If the minimum possible date happens to fall on a weekend(Sat or Sun) after adding 1 day, Display the next working day i.e Monday
如果最短的日期正好是假期,请显示下一个工作日。 (假日1.1、1.5、3.10、25.12、26.12)
If the minimum possible date happens to fall on a Holiday, display the next working day. (Holidays 1.1 , 1.5 , 3.10 , 25.12 , 26.12)
如果最短日期恰好是加了1天后的周末(星期六或星期日) ,然后第二天是假期,然后显示下一个工作日。例如:+1天后(如果可能的最小日期是星期六),我们将不得不显示星期一。但是,如果星期一恰好是假期,那么我们必须显示星期二。
If the minimum possible date happens to fall on a weekend(Sat or Sun) after adding 1 day, and the day after that is a holiday then show the next working day. Eg: After +1 day if min possible day is Saturday, we will have to display Monday. But if Monday happens to be a Holiday then we have to display Tuesday.
我已经尝试了上述解决方案通过有多个if和else案例来解决问题,但是只是想知道是否有任何通用且优美的方式?
I have tried a solution to the above problem by having multiple if and else cases, but just wondering if there is any generic and graceful way of doing it?
我尝试过
var Holidays = new List<DateTime>();
Holidays.Add(new DateTime(DateTime.Now.Year,1,1));
Holidays.Add(new DateTime(DateTime.Now.Year,1,5));
Holidays.Add(new DateTime(DateTime.Now.Year,3,10));
Holidays.Add(new DateTime(DateTime.Now.Year,12,25));
if(date.DayOfWeek === DayOfWeek.Saturday || date.DayOfWeek === DayOfWeek.Sunday)
{
//Logic to add +1 and again some logic to check for weekends and weekdays
}
else if(holidays.Contain(date))
{
//Logic to add +1 and again some logic to check for weekends and weekdays
}
推荐答案
基本上,您想获得下一个工作日。因此,您可以在这种情况下循环运行,将当前日期添加1天
Basically you want to get the next working day. So you could loop on this condition adding 1 day to the current date
do {
date = date.AddDays(1);
} while(IsHoliday(date) || IsWeekend(date));
在上一个代码中, IsHoliday
是一个谓词告诉日期是否是假期。例如,无耻地重用您的代码:
In the previous code IsHoliday
is a predicate telling if a date is holiday. For instance, shamelessly reusing your code:
class Program
{
private static readonly HashSet<DateTime> Holidays = new HashSet<DateTime>();
private static bool IsHoliday(DateTime date)
{
return Holidays.Contains(date);
}
private static bool IsWeekend(DateTime date)
{
return date.DayOfWeek == DayOfWeek.Saturday
|| date.DayOfWeek == DayOfWeek.Sunday;
}
private static DateTime GetNextWorkingDay(DateTime date)
{
do
{
date = date.AddDays(1);
} while (IsHoliday(date) || IsWeekend(date));
return date;
}
static void Main(string[] args)
{
Holidays.Add(new DateTime(DateTime.Now.Year, 1, 1));
Holidays.Add(new DateTime(DateTime.Now.Year, 1, 5));
Holidays.Add(new DateTime(DateTime.Now.Year, 3, 10));
Holidays.Add(new DateTime(DateTime.Now.Year, 12, 25));
var dt = GetNextWorkingDay(DateTime.Parse(@"2015-10-31"));
Console.WriteLine(dt);
Console.ReadKey();
}
}
这篇关于如何获得下一个工作日,周末和节假日除外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!