这里对特殊日期采用了模拟的方式,在实际开发中当然这些数据是从数据库中读取,调用方法时 只需传入开始时间(一般当前) 和N(代表N个工作日)
/// <summary>
/// 获取时间
/// </summary>
/// <param name="dt">当前时间</param>
/// <param name="n">N个工作日</param>
/// <returns></returns>
public static string Dt(DateTime dt, int n)
{
WorkDay workDay = new WorkDay();
//特殊日期(此处数据为模拟数据)
List<WorkDay> workDayList = new List<WorkDay>();
workDayList.Add(new WorkDay { Key=1,Dt=DateTime.Now.AddDays(1),type=WorkDayType.休息});
workDayList.Add(new WorkDay { Key = 2, Dt = DateTime.Now.AddDays(2), type = WorkDayType.休息 });
workDayList.Add(new WorkDay { Key = 3, Dt = DateTime.Now.AddDays(3), type = WorkDayType.工作 });
workDayList.Add(new WorkDay { Key = 4, Dt = DateTime.Now.AddDays(4), type = WorkDayType.工作 });
workDayList.Add(new WorkDay { Key = 5, Dt = DateTime.Now.AddDays(5), type = WorkDayType.休息 });
workDayList.Add(new WorkDay { Key = 6, Dt = DateTime.Now.AddDays(6), type = WorkDayType.休息 });
workDayList.Add(new WorkDay { Key = 7, Dt = DateTime.Now.AddDays(7), type = WorkDayType.休息 });
workDayList.Add(new WorkDay { Key = 8, Dt = DateTime.Now.AddDays(8), type = WorkDayType.休息 });
workDayList.Add(new WorkDay { Key = 9, Dt = DateTime.Now.AddDays(9), type = WorkDayType.休息 });
workDayList.Add(new WorkDay { Key = 10, Dt = DateTime.Now.AddDays(10), type = WorkDayType.休息 });
workDayList.Add(new WorkDay { Key = 11, Dt = DateTime.Now.AddDays(11), type = WorkDayType.休息 });
workDayList.Add(new WorkDay { Key = 12, Dt = DateTime.Now.AddDays(12), type = WorkDayType.休息 });
int d = 0;
if (n<=0)
{
d = 0;
return dt.AddDays(d).ToShortDateString();
}
for (int i = 1; i >0; i++)
{ var gg = workDayList.Where(x => x.Dt.ToShortDateString() == dt.AddDays(i).ToShortDateString()).FirstOrDefault();
if ((int)dt.AddDays(i).DayOfWeek == 0 || (int)dt.AddDays(i).DayOfWeek == 6)
{
//如果为周六或者周末 则判断是否为工作时间
if (gg != null)
{
if (gg.type == WorkDayType.工作)
{
d++;
}
}
}
else //不是周末和周六
{
if (gg != null)
{
if (gg.type == WorkDayType.休息)
{
}
else
{
d++;
}
}
else
{
d++;
}
}
if (d==n)
{
return dt.AddDays(i).ToShortDateString();
}
}
return dt.AddDays(d).ToShortTimeString();//这句代码没实际意义,只为编译器通过
}
当然需要添加一个类 和一个枚举
public class WorkDay
{
public DateTime Dt { get; set; }
public int Key { get; set; }
public WorkDayType type { get; set; }
}
public enum WorkDayType
{
工作,休息
}