Link to home
Start Free TrialLog in
Avatar of lololo50
lololo50

asked on

How to add time to TDateTime

Hi

I need to add some time to a TDateTime type.
for eg. how can i add 150 secs to it ??

Thanks for any help
Avatar of LMuadDIb
LMuadDIb
Flag of United States of America image

there are a few ways of doing it, using EncodeTime / DecodeTime / RecodeTime functions
but you would have to decode your tdatetime, adjust the time, then encode
example:

var
  Hr,Min,Sec,MSec : Word;
begin
  DecodeTime(MyTime,Hr,Min,Sec,MSec);
  Sec := Sec + 1;
  MyTime:=EncodeTime(Hr,Min,Sec,MSec);

try this way:

procedure TForm1.Button1Click(Sender: TObject);
var
  dt, newdt:  TDateTime;
  s: word;
begin
dt := EncodeDate(1999, 12, 25) +  EncodeTime(20, 5, 30, 0);
           s := 137 {secs};
      newdt := dt + s / 86400 {seconds/day};
      ShowMessage( FormatDateTime('dd mmm yyyy, hh:nn:ss', newdt) );

end;
crap, hit the submit button before finishing the post. Here is the same info but a bit more clear:
the following code will ADD 150 seconds to a tdatetime...  to substract, just change "+" to "-"... thats all

procedure TForm1.Button1Click(Sender: TObject);
var
  dt, newdt:  TDateTime;
  s: word; //additional seconds you want to add to the tdatetime
begin
     dt := EncodeDate(1999, 12, 25) +  EncodeTime(20, 5, 30, 0); //your tdatetime to adjust
     s := 150; {secs}
     newdt := dt + s / 86400 {seconds/day};
     ShowMessage( FormatDateTime('dd mmm yyyy, hh:nn:ss', newdt) );
end;

//-- to add Years, Weeks, Months, Days, Hours, Mins, Secs
newdt := IncMonth(dt, y*12 {months/year});
newdt := dt + 7 {days/week}*w;
newdt := IncMonth(dt, m);
newdt := dt + d;
newdt := dt + h / 24 {hours/day};
newdt := dt + m / 1440 {minutes/day};
newdt := dt + s / 86400 {seconds/day};
ASKER CERTIFIED SOLUTION
Avatar of RickJ
RickJ

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of lololo50
lololo50

ASKER

@RickJ
exactly what i was looking for, and works great
thanks

@LMuadDib
Your solution is also (maybe - didn't check it) usable, but it's to much work (less code is better, and my proggy code is easier to read). That's why i choose RickJ's answer.
Thanks.
Glad I could help.