[Lazarus] DateDif function needed

John Landmesser JohnML at online.de
Sat Nov 9 14:01:47 CET 2013


On 09.11.2013 06:55, leledumbo wrote:
>    Date1 := EncodeDate(2012,12,21);
>    Date2 := EncodeDate(2013,01,01);

Your code Result is: 1900 Years, 1 Month, 10 days and thats incorrect.

I thought about it some time and found a solution:

Think of the age of an employe! We have now() and his birthday.
How old is he in Years , Months and days?

my code:

uses DateUtils;

function TForm1.CalcDateDif(von, bis: TDateTime): String;
var
   Year, Month, Day: longint;
   YearVon, MonthVon, DayVon : word;
   YearBis, MonthBis, DayBis : word;

begin

   DecodeDate(von, YearVon, MonthVon, DayVon);
   DecodeDate(bis, YearBis, MonthBis, DayBis);

   // whole year:
    year := YearsBetween(von,bis);

   // How many months more than months in "year"
    Month := MonthsBetween(von,bis) - (year * 12);

   // Special case: December of previous year as "von"  and not a whole 
Month until "bis": 21.12.2012 until 01.01.2013
   if  (YearBis - YearVon = 1) and (MonthVon = 12) then
    begin
      Day :=  DaysBetween(von,EndOfAYear(YearVon)) + DayOfTheYear(bis);
    end
    else
       Day := DaysBetween(EnCodeDate(YearBis,MonthVon, DayVon), bis) ;

     Result := IntToStr(year) + ' Jahr(e) ';

      Result := Result + IntToStr(Month) + ' Monat(e) ';

     Result := Result + IntToStr(Day) + ' Tag(e) ';

end;

// I have to test that later again, but i think thats ok now?!!
// Going jogging now :-))

But i'm really wondering that Freepascal does not have such a function?!!






More information about the Lazarus mailing list