[Lazarus] DateDif function needed

Hans-Peter Diettrich DrDiettrich1 at aol.com
Sun Nov 10 06:53:10 CET 2013


waldo kitty schrieb:

>>    DecodeDate(Date2 - Date1,Y,M,D);
>>    // you have them in Y, M and D, respectively

> yeah, that doesn't work...
> 
> Y = 1900
> M = 1
> D = 10
> 
> Y should be 1 in this case...

I'm not sure, IMO also M and D should be decremented by 1.

> ideally, real numbers would be used so that fractions of years, months 
> and days can be determined ;)

Of course real numbers are used. Problem is the time *base* (calendar 
origin), that (here) translates zero into year 1900, and IMO also 
offsets the month and day by 1. Delphi may yield a different year, AFAIR 
its calendar is based on 1899-12-30 12:00.

The day *difference* is the integral part of real difference, i.e. 
trunc(Date2-Date1). But for the elimination of all offsets I'd suggest 
to determine all base values, and subtract these from the individual 
values. Something like
   DecodeDate(0.0, Y0,M0,D0);
   DecodeDate(Date2-Date1,Y,M,D);
   dec(Y,Y0); dec(M,M0); dec(D,D0);

But this still wouldn't be correct, because then the leap years 
(february length) of 1900 ff. are taken into account, not those of the 
start year. Better should be:
   DecodeDate(Date1, Y0,M0,D0);
   DecodeDate(Date2,Y,M,D);
   dec(Y,Y0); dec(M,M0); dec(D,D0);
with the ugly effect that now M and D can become negative and have to be 
adjusted again.

So the general question arises: do you want a date difference expressed 
in uniform years (of 360 days) and months (of 30 days), or in variable 
calendar months and years?

IMO a dedicated Age function should be added, that determines e.g. the 
age of a person properly. This function must return exactly zero months 
and days for dates of the same month and day (birthday), regardless of 
the years. Looks easy to accomplish, but is not really :-(

DoDi





More information about the Lazarus mailing list