Calculate Days Between Two Dates
Asked Answered
S

2

5

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

Sangsanger answered 7/10, 2015 at 11:30 Comment(2)
You're calculating a number (39), then storing the result in a date and so it's displaying as a date (07.02.1900).Calandra
Ask yourself how DateToStr knows you want to interpret the value as a time span or a date?Lancet
C
16

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;
Cliff answered 7/10, 2015 at 13:16 Comment(1)
Thanks for everyone I understand my mistake. And problem solvedSangsanger
W
0

I had the same problem in one of my projects. but after a little search in Delphi help, I find out Delphi has a rich set of functions on dates. Anyway you can use from 'DaysBetween' function to solve your problem. My code was something like this:

procedure TForm1.btnResultClick(Sender: TObject);
var
  FirstDate, SecondDate: TDateTime;
  format:TFormatSettings;
  intDays: Integer;
begin
  format:= TFormatSettings.Create();
  format.ShortDateFormat :=  'yyyy/mm/dd';
  FirstDate := StrToDate(eFirstDate.Text,format);
  SecondDate := StrToDate(eSecondDate.Text,format);
  intDays:= DaysBetween(FirstDate,SecondDate);
  eFinalDate.Text:= intToStr(intDays);
end;
Winterwinterbottom answered 24/6, 2017 at 8:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.