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?
2
votes
3 Answers
8
votes
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;
8
votes
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);