我用它来获得一个月的第一个工作日。但是,如何在2014年到2030年之间使用日期范围来获得每个月的第一个工作日。
public static DateTime GetFirstBussinessDayCurrentMonth(DateTime[] holidays)
{
return
Enumerable.Range(1, DateTime.DaysInMonth(DateTime.Today.Year, DateTime.Today.Month))
.Select(day => new DateTime(DateTime.Today.Year, DateTime.Today.Month, day))
.Where(
dt =>
dt.DayOfWeek != DayOfWeek.Sunday && dt.DayOfWeek != DayOfWeek.Saturday
&& (holidays == null || !holidays.Any(h => h.Equals(dt))))
.Min(d => d.Date);
}
答案 0 :(得分:0)
您必须修改您的方法以使用您投入的任何年份和月份,而不仅仅是当前日期:(接受一年和一个月,并使用那些而不是DateTime.Today)
public static DateTime GetFirstBussinessDayInMonth(int month, int year, DateTime[] holidays)
{
return Enumerable.Range(1, DateTime.DaysInMonth(year, month))
.Select(day => new DateTime(year, month, day))
.Where(dt => dt.DayOfWeek != DayOfWeek.Sunday
&& dt.DayOfWeek != DayOfWeek.Saturday
&& (holidays == null || !holidays.Any(h => h.Equals(dt))))
.Min(d => d.Date);
}
然后每年对您感兴趣的每个月拨打一次。这里我们计算从2014年到2030年每个月的第一个工作日,并将它们全部添加到日期时间列表中。< / p>
var startYear = 2014;
var endYear = 2030;
var businessDays = new List<DateTime>();
for (var year = startYear; year <= endYear; year++)
{
businessDays.AddRange(
Enumerable.Range(1, 12)
.Select(month => GetFirstBussinessDayInMonth(month, year, holidays)));
// not sure where 'holidays' comes from.. I'll assume it's defined
}