我需要计算两个给定日期之间的工作日(工作日)计数。工作日是一周中的所有日子,但周六和周日除外。我不在考虑将假期计入这一数字。

如何计算两个日期之间的工作日数?

最佳答案

您需要使用 DayOfTheWeek (来自DateUtils单元)和一个计数器,从开始日期到结束日期进行迭代。 (您可能还需要一个假期表,以将假期也排除在表外。)

function BusinessDaysBetween(const StartDate, EndDate: TDateTime): Integer;
var
  CurrDate : TDateTime;
begin
  CurrDate := StartDate;
  Result := 0;
  while (CurrDate <= EndDate) do
  begin
    // DayOfTheWeek returns 1-5 for Mon-Fri, so 6 and 7 are weekends
    if DayOfTheWeek(CurrDate) < 6 then
      Inc(Result);
    CurrDate := CurrDate + 1;
  end;
end;

您可以通过不必担心参数的顺序来增强此功能(换句话说,无论start是在end之前还是end在start之前都没有关系,该函数仍然可以使用):
function BusinessDaysBetween(const FirstDate, SecondDate: TDateTime): Integer;
var
  CurrDate : TDateTime;
  StartDate, EndDate: TDateTime;
begin
  if SecondDate > FirstDate then
  begin
    StartDate := FirstDate;
    EndDate := SecondDate;
  end
  else
  begin
    StartDate := SecondDate;
    EndDate := FirstDate;
  end;

  CurrDate := StartDate;
  Result := 0;

  while (CurrDate <= EndDate) do
  begin
    if DayOfTheWeek(CurrDate) < 6 then
      Inc(Result);
    CurrDate := CurrDate + 1;
  end;
end;

10-08 17:21