stuartclennett

Date Difference in Months & Days

Feb 1st, 2019
597
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 1.76 KB | None | 0 0
  1. function TTDateDiffUtils.DateAddMonths(startDate: TDateTime; monthCount: integer; sticky: boolean): TDateTime;
  2. var
  3.   RY,RM,RD : word;  // result date
  4.   SY,SM,SD : word;  // start date
  5. begin
  6.   result := IncMonth(startDate, monthCount);
  7.   if (sticky) then // stick
  8.   begin
  9.     DecodeDate(result, RY,RM,RD);
  10.     DecodeDate(startDate, SY,SM,SD);
  11.     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
  12.       result := EncodeDate(RY, RM, SD);
  13.   end;
  14. end;
  15.  
  16. function TTDateDiffUtils.DateDiffString(aThen, aNow: TDateTime; sticky : boolean; out years, months, days, hours : integer ): string;
  17. var
  18.   LNow, LThen, LRunning: TDateTime;
  19.   testDate : TDateTime;
  20.   monthCount : integer;
  21. begin
  22.  
  23.   //  https://secondboyet.com/Articles/PublishedArticles/Calculatingthenumberofmon.html  //
  24.  
  25.   result := '';
  26.  
  27.   if aThen > aNow then
  28.   begin
  29.     LNow := aThen;
  30.     LThen := aNow;
  31.   end else
  32.   begin
  33.     LNow := aNow;
  34.     LThen := aThen;
  35.   end;
  36.  
  37.   monthCount := Trunc((LNow-LThen) / 31);  // make a guess -- it'll be close but not 100% accurate
  38.   testDate := DateAddMonths(LThen, monthCount, sticky);
  39.   while (testDate < LNow) do
  40.   begin
  41.     Inc(monthCount);
  42.     testDate := DateAddMonths(LThen, monthCount, sticky);
  43.   end;
  44.  
  45.   if (testDate = LNow) then
  46.   begin
  47.     months := monthCount;
  48.     days := 0;
  49.   end else
  50.   begin
  51.     // testDate > LNow = we've exceeded the second date so backup there sparky and fix the values
  52.     Dec(monthCount);
  53.     testDate := DateAddMonths(LThen, monthCount, sticky);
  54.     months := monthCount;
  55.     days := Trunc((LNow-testDate));  // this is the remainder days
  56.   end;
  57.  
  58.   result := format('%d months %d days', [months, days]);
  59. end;
Advertisement