Reputation: 9094
If I need to get a date like 12/30/2013
and add 10 days at 8pm, How can I do that in Delphi if I have a TDateTime
variable with that first date?
Upvotes: 6
Views: 31592
Reputation: 51
Here's how to do it:
uses
SysUtils, DateUtils;
...
procedure TForm1.Button1Click(Sender: TObject);
var
DT : TDateTime;
begin
DT := StrToDate('30/12/2013');
DT := DT + 10;
ReplaceTime(DT, EncodeTime(20, 0, 0, 0));
ShowMessage(DateTimeToStr( DT ));
end;
Upvotes: 0
Reputation: 612954
The DateUtils unit has a swath of helpers that allow you to insulate yourself from the way TDateTime is encoded. For instance:
uses
SysUtils, DateUtils;
....
var
DT: TDateTime;
....
DT := EncodeDate(2013, 12, 30); // Dec 30 2013 @ 12AM
DT := IncDay(DT, 10);
DT := IncHour(DT, 20);
This is perhaps a little long-winded but I chose that approach to illustrate both IncDay and IncHour. I do recommend studying the contents of DateUtils to familiarise yourself with all of its functionaility.
Another way to do this would be like so:
DT := EncodeDateTime(2013, 12, 30, 20, 0, 0, 0); // Dec 30 2013 @ 8PM
DT := IncDay(DT, 10);
Or even:
DT := IncDay(EncodeDateTime(2013, 12, 30, 20, 0, 0, 0), 10);
Upvotes: 13
Reputation: 596166
You can use the +
operator to add an integral number of days, and use SysUtils.ReplaceTime()
to change the time, eg:
uses
..., SysUtils;
var
DT: TDateTime;
begin
DT := EncodeDate(2013, 12, 30); // Dec 30 2013 @ 12AM
DT := DT + 10; // Jan 9 2014 @ 12AM
ReplaceTime(DT, EncodeTime(20, 0, 0, 0)); // Jan 9 2014 @ 8PM
end;
Upvotes: 12