Mega Code Archive

 
Categories / Delphi / Examples
 

Next or Prev working Day

Title: Next or Prev working Day Question: How to calculate the next/prev working day starting from a given date. working days are monday to friday. This article replaces the obsolete artice 2387 Answer: type // callback function for holidays THolidayCallback = function(const d:TDateTime):boolean; function PrevWorkingDay(const date:TDateTime; callback:THolidayCallback):TDateTime; begin Result := Int(date) - 1.0; // yesterday 0:00 if Assigned(callback) then while (DayOfWeek(Result) in [1,7]) or callback(Result) do Result := Result - 1.0 else while (DayOfWeek(Result) in [1,7]) do Result := Result - 1.0; end; function NextWorkingDay(const date:TDateTime; callback:THolidayCallback):TDateTime; begin Result := Int(date) + 1.0; // tomorrow 0:00 if Assigned(callback) then while (DayOfWeek(Result) in [1,7]) or callback(Result) do Result := Result + 1.0 else while (DayOfWeek(Result) in [1,7]) do Result := Result + 1.0; end; =========================================================================== // example for the callback function function IsHoliday(const d:TDateTime):boolean; var year, month, day; begin DecodeDate(d, year, month, day); if (month = 12) and ((day=25) or (day=26)) then result := True // christmas else if (month=12) and (day=31) then result := True // sylvester else if (month=1) (day=1) then result := True; // more queries here // e.g. a lookup in a database end;