C# 自年月日起第n天
我用它来获得每月的第一个工作日。但我如何使用日期范围来获取2014年到2030年的每月第一个工作日呢C# 自年月日起第n天,c#,linq,C#,Linq,我用它来获得每月的第一个工作日。但我如何使用日期范围来获取2014年到2030年的每月第一个工作日呢 public static DateTime GetFirstBussinessDayCurrentMonth(DateTime[] holidays) { return Enumerable.Range(1, DateTime.DaysInMonth(DateTime.Today.Year, DateTime.Today.Month))
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);
}
您必须修改您的方法以处理您抛出的任何年份和月份,而不仅仅是当前日期:接受年份和月份,并使用它们而不是DateTime 然后在你感兴趣的每年的每个月打一次电话。这里我们计算2014年至2030年每个月的第一个工作日,并将其全部添加到日期时间列表中
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
}
假日数组是如何填充的?为什么不先使用Min而不是Min,因为日期是有序的。这样,您就不必创建所有的日期来确定最早的日期。
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
}