我一直在這裏搜索以找到解決問題的方法,但迄今未找到任何解決方案。 嗯,我發現了一些可以工作的parcial函數,但由於我是C#中的新手,我需要一些幫助來合併所有代碼才能工作。 因此,我需要計算兩個日期之間的工作日,忽略週末和葡萄牙假期。 對於假期,我有這樣的代碼,返回所有葡萄牙假期:計算特定國家/地區的無假期工作日
public static List<DateTime> GetHolidays(int year)
{
List<DateTime> result = new List<DateTime>();
result.Add(new DateTime(year, 1, 1)); //New Year Day
result.Add(new DateTime(year, 4, 25)); //Dia da Liberdade (PT)
result.Add(new DateTime(year, 5, 1)); //Labour Day
result.Add(new DateTime(year, 6, 10)); //Dia de Portugal (PT)
result.Add(new DateTime(year, 8, 15)); //Assumption of Mary
result.Add(new DateTime(year, 10, 5)); //Implantação da república (PT)
result.Add(new DateTime(year, 11, 1)); //All Saints' Day
result.Add(new DateTime(year, 12, 1)); //Restauração da independência (PT)
result.Add(new DateTime(year, 12, 8)); //Imaculada Conceição (PT?)
result.Add(new DateTime(year, 12, 25)); //Christmas
foreach (DateTime holiday in variable)
{
if (!result.Contains(holiday)) //if the holiday already exists then don't add
{
result.Add(holiday);
}
}
return result;
}
而我的函數來計算工作日內這一個我發現這裏的計算器:
public static int BusinessDaysUntil(this DateTime firstDay, DateTime lastDay, params DateTime[] bankHolidays)
{
firstDay = firstDay.Date;
lastDay = lastDay.Date;
if (firstDay > lastDay)
throw new ArgumentException("Incorrect last day " + lastDay);
TimeSpan span = lastDay - firstDay;
int businessDays = span.Days + 1;
int fullWeekCount = businessDays/7;
// find out if there are weekends during the time exceedng the full weeks
if (businessDays > fullWeekCount * 7)
{
// we are here to find out if there is a 1-day or 2-days weekend
// in the time interval remaining after subtracting the complete weeks
int firstDayOfWeek = (int)firstDay.DayOfWeek;
int lastDayOfWeek = (int)lastDay.DayOfWeek;
if (lastDayOfWeek < firstDayOfWeek)
lastDayOfWeek += 7;
if (firstDayOfWeek <= 6)
{
if (lastDayOfWeek >= 7)// Both Saturday and Sunday are in the remaining time interval
businessDays -= 2;
else if (lastDayOfWeek >= 6)// Only Saturday is in the remaining time interval
businessDays -= 1;
}
else if (firstDayOfWeek <= 7 && lastDayOfWeek >= 7)// Only Sunday is in the remaining time interval
businessDays -= 1;
}
// subtract the weekends during the full weeks in the interval
businessDays -= fullWeekCount + fullWeekCount;
// subtract the number of bank holidays during the time interval
foreach (DateTime bankHoliday in bankHolidays)
{
DateTime bh = bankHoliday.Date;
if (firstDay <= bh && bh <= lastDay)
--businessDays;
}
return businessDays;
}
但是,該代碼使用DateTime [] bankHolidays和我需要改變它以考慮我的假期(GetHolidays())。 你能幫我改變一下代碼嗎? 謝謝
我沒有看到一個問題,這是一個任務...請嘗試一下自己,當你偶然發現一個具體的問題,你可以問一個問題。 –
看來你的問題的答案很簡單:用foreach(DateTime bankHoliday in GetHolidays(2016))替換'foreach(DateTime bankHoliday in bankHolidays)'' –