Topic: Function MonthsBetween()

i try use MVD Function MonthsBetween()

MonthsBetween('2017-10-01','2016-10-01') 

result

11

why not result

12

Error ???

My Visual Database : I Love You
Easy For Beginner Student For Me

Re: Function MonthsBetween()

Hi,
ShowMessage(IntToStr(MonthsBetween(EncodeDate(2017,1,1),EncodeDate(2016,1,1))));  ==> 12
ShowMessage(IntToStr(MonthsBetween(EncodeDate(2017,2,1),EncodeDate(2016,2,1))));  ==> 12
ShowMessage(IntToStr(MonthsBetween(EncodeDate(2017,3,1),EncodeDate(2016,3,1))));  ==> 11
...
ShowMessage(IntToStr(MonthsBetween(EncodeDate(2017,12,1),EncodeDate(2016,12,1))));  ==> 11

That's weird... but
ShowMessage(IntToStr(MonthsBetween(EncodeDate(2017,1,2),EncodeDate(2016,1,1))));  ==> 12
...
ShowMessage(IntToStr(MonthsBetween(EncodeDate(2017,12,2),EncodeDate(2016,1,1))));  ==> 12

So if you want to count the month add a day to the ANow parameter.

This occurs because : MonthsBetween returns the number of whole months between ANow and AThen. This number is an approximation, based on an average number of days of 30.4375 per month (average over 4 years). This means the fractional part of a month is dropped (==> https://www.freepascal.org/docs-html/rt … tween.html.

Use this function (==> http://www.delphigroups.info/2/5b/290654.html) :

function MonthsBetweenEx(date1, date2: TDateTime): integer;
var
  y1, m1, d1, y2, m2, d2, year: word;
  dt1, dt2: TDateTime;
begin 
  If date1 > date2 then begin
    dt1 := date2; 
    dt2 := date1; 
  end else begin 
    dt1 := date1; 
    dt2 := date2; 
  end; 
  DecodeDate(dt1, y1, m1, d1); 
  DecodeDate(dt2, y2, m2, d2); 
  Result := 0; 
  if y1 = y2 then begin 
    // Same year 
    if m1 = m2 then begin 
      // Same month 
      Result := 0; 
    end else begin 
      Result := m2 - m1; 
      // More days in month 1 than 2, decrement by one. 
      if d1 > d2 then inc(Result, -1); 
    end; 
  end else begin
    // Years not equal.
    Result := m2 - m1 + ((y2 - y1) * 12);
    if d1 > d2 then inc(Result, -1); 
  end; 
end;


Kind regards,
jihem

while(! success=retry());
https://jihem.itch.io