Search code examples
delphidelphi-7

How to add only some days to date-time variable?


When I need to increase date 1/1/2016 by 7 days, I can simply do:

IncDay(myDate, 7); // Result 8/1/2016

What do I do, if I need to ignore some days (e.g. Saturdays), so the Result is 10/1/2016 ?


Solution

  • This adds a day to the calculation for each Saturday found in the ANumberOfDays range:

    {.$DEFINE UNCLEAR_WHAT_YOU_R_ASKING}
    
    function IncDayIgnoringSaturdays(const AValue: TDateTime; const ANumberOfDays: Integer = 1): TDateTime;
    var
      i, j: Integer;
    begin
      i := ANumberOfDays;
      j := 0;
      Result := AValue;
      while i > 0 do begin
        Result := IncDay(Result);
        if DayOfTheWeek(Result) = DaySaturday then
          Inc(j);
        Dec(i);
      end;
      Result := IncDay(Result, j);
    
      {$IFDEF UNCLEAR_WHAT_YOU_R_ASKING}
      if DayOfTheWeek(Result) = DaySaturday then
        Result := IncDay(Result);
      {$ENDIF}
    end;
    
    begin
      WriteLn(DateTimeToStr(IncDayIgnoringSaturdays(StrToDateTime('1/1/2016'), 7)));
      WriteLn(DateTimeToStr(IncDayIgnoringSaturdays(StrToDateTime('1/1/2016'), 14)));
      ReadLn;
    end.
    

    EDIT
    The above may return a date on Saturday or not, depending on the UNCLEAR_WHAT_YOU_R_ASKING conditional define.