Date Calculation

I need to calculate how many days have elapsed between two given dates. i.e...

29/11/1999 - 21/11/1999 = 8

Cheers, Chris.
LVL 1
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
Tdatetimes are stored as floats with the integer portion representing the day and the fractional part the time.  So you simple subtract one date from the other and add 1.

Here is code for a unit that does this.  Drop 2 datetimepickers and a button. The trunc call is to make sure there is no time component included in the date.

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls;

type
TForm1 = class(TForm)
DateTimePicker1: TDateTimePicker;
DateTimePicker2: TDateTimePicker;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{\$R *.DFM}

procedure TForm1.Button1Click(Sender: TObject);
begin
showmessage(inttostr(trunc(datetimepicker1.date - datetimepicker2.date + 1)));
end;

end.
0
Author Commented:
Heapster,

this seems to work but it returns negative values

i.e. -17 days

any ideas why?

Cheers, Chris.
0
Commented:
Try

Function DiffInDays(T1,T2 : TDateTime) : Integer;
begin
if (T1 < T2) then
result := trunc(T2)-trunc(T1);
else
result := trunc(T1)-trunc(T2);
end;

This will always return a positive result in days.

I disagree with the +1 that Heapster added - the result here should be zero when the same day is passed for both parameters, we're not counting one of the days, but the difference in days.
0

Experts Exchange Solution brought to you by