• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 581
  • Last Modified:

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
0
lololo50
Asked:
lololo50
  • 2
  • 2
1 Solution
 
LMuadDIbCommented:
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;
0
 
LMuadDIbCommented:
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};
0
 
RickJCommented:
You could use the IncSecond funtion i.e  

IncSecond(DateToInc, NoSecsToInc) ;

Check in the DateUtils unit. It has various similar routines. (Delphi 7)
0
 
lololo50Author Commented:
@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.
0
 
RickJCommented:
Thanks.
Glad I could help.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now