Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function TTDateDiffUtils.DateAddMonths(startDate: TDateTime; monthCount: integer; sticky: boolean): TDateTime;
- var
- RY,RM,RD : word; // result date
- SY,SM,SD : word; // start date
- begin
- result := IncMonth(startDate, monthCount);
- if (sticky) then // stick
- begin
- DecodeDate(result, RY,RM,RD);
- DecodeDate(startDate, SY,SM,SD);
- if DaysInAMonth(RY, RM) = SD then // i.e. if the day portion from the startDate === the end of the new month then make the result be the end of the month
- result := EncodeDate(RY, RM, SD);
- end;
- end;
- function TTDateDiffUtils.DateDiffString(aThen, aNow: TDateTime; sticky : boolean; out years, months, days, hours : integer ): string;
- var
- LNow, LThen, LRunning: TDateTime;
- testDate : TDateTime;
- monthCount : integer;
- begin
- // https://secondboyet.com/Articles/PublishedArticles/Calculatingthenumberofmon.html //
- result := '';
- if aThen > aNow then
- begin
- LNow := aThen;
- LThen := aNow;
- end else
- begin
- LNow := aNow;
- LThen := aThen;
- end;
- monthCount := Trunc((LNow-LThen) / 31); // make a guess -- it'll be close but not 100% accurate
- testDate := DateAddMonths(LThen, monthCount, sticky);
- while (testDate < LNow) do
- begin
- Inc(monthCount);
- testDate := DateAddMonths(LThen, monthCount, sticky);
- end;
- if (testDate = LNow) then
- begin
- months := monthCount;
- days := 0;
- end else
- begin
- // testDate > LNow = we've exceeded the second date so backup there sparky and fix the values
- Dec(monthCount);
- testDate := DateAddMonths(LThen, monthCount, sticky);
- months := monthCount;
- days := Trunc((LNow-testDate)); // this is the remainder days
- end;
- result := format('%d months %d days', [months, days]);
- end;
Advertisement