Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate Days Between Two Dates

Please help me find days between two dates.

I have two objects TDBDateEdit date1 and date2.

procedure Torder_form.date2Click(Sender: TObject);
var d3: TDateTime;
begin 
    d3:=date2.date - date1.date;
    showmessage(datetostr(d3));
end.

I put to date1 = 07.10.2015

to date2 - 15.11.2015

Result must be: 39

But program gives me result: 07.02.1900


I found DaysBetween function. and I changed my codes like that

procedure Torder_form.date2Click(Sender: TObject);
var d3: TDateTime;
begin 
    d3:=DaysBetween(date2.date,date1.date);
    showmessage(datetostr(d3));
end.

But programs says Result: 07.02.1900

like image 520
Hayrulla Melibayev Avatar asked Dec 10 '22 20:12

Hayrulla Melibayev


1 Answers

You're trying to store a non-date value (the number of days between two dates) in a TDateTime value. Since you don't want a date, use a double instead, and interpret it as a double:

var
  DaysDiff: Double;
begin
  DaysDiff := Date2.Date - Date1.Date;
  ShowMessage(FloatToStr(DaysDiff));
end;

Better yet, use the functions in DateUtils to do the work for you. If you need just whole days, use DaysBetween:

var
  DaysDiff: Integer;
begin
  DaysDiff := DaysBetween(Date2.Date, Date1.Date);
  ShowMessage(IntToStr(DaysDiff));
end;

If you need fractional (partial) days, use DaySpan:

var
  DaysDiff: Double;
begin
  DaysDiff := DaySpan(Date2.Date, Date1.Date);
  ShowMessage(FloatToStr(DaysDiff));
end;
like image 73
Ken White Avatar answered Dec 21 '22 19:12

Ken White