Last Updated:

Date & Time in Delphi

Date & Time in Delphi

Why have a textbook only on dates and times? Because it's an amazingly complex and rich subject. And very useful, especially since Delphi provides extensive support for calculations, transformations and names.

TDateTime data type

 

The date and time processing depends on the TDateTime variable. It is used to store a combination of date and time. It is also used to store only date or time values—the time and date values are ignored accordingly. TDateTime is defined in the system unit. Date constants and subroutines are defined in SysUtils and DateUtils units.

Let's look at some simple examples of assigning a value to the TDateTime variable:

var
data1, data2, data3 : TDateTime; TDateTime variables
begin
data1 := Yesterday; Sets the beginning of yesterday
data2 := Today; The current date
is set to data3 := Tomorrow; Sets the beginning of
tomorrow's data4 := Right now; The current end date and time
is set;

data1 is set to something like 04/01/2021 00:00:00
data2 is installed on something like 05/01/2021 00:00:00
data3 is installed on something like 06/01/2021 00:00:00
data4 is installed on something like 05/01/2021 19:33:15

 

Note:
The beginning of the day is often referred to as midnight in the Delphi documentation, but this is misleading as it will be midnight of the wrong day.

 

Some named date values

 

Delphi provides some useful names for days and months, saving you the boredom of defining them in your own code. Here they are:

Short and long month names

 

Note that these arrays of month names begin with index = 1.

var
month : Integer;
begin
for month := 1 to 12 do // Display the short and long month names
begin
ShowMessage(ShortMonthNames[month]);
ShowMessage(LongMonthNames[month]);
end;
end;

The ShowMessage procedure displays the following information:

January
February
March
April
May
June
July
August
September
October
November
December

Short and long names of days

 

It is important to note that these daily arrays start with an index of 1 = Sunday. It's not a very good standard (it doesn't comply with ISO 8601), so be careful when used with ISO 8601 compliant procedures like DayOfTheWeek.

var
day : Integer;
begin
for day := 1 to 12 do // Display short and long names
begin
ShowMessage;
ShowMessage(Long titles[day]);
end;
end;

The ShowMessage procedure displays the following information:

Mon
Monday
Tue
Tuesday
Wed
Wednesday
Thu
Thursday
Fri
Friday
Sat
Saturday
Sun
Sunday

Date and time calculations

The biggest advantage of TDateTime is the range of calculations that Delphi can do for you. They can be found on the Delphi Basics homepage in the dates and times/calculations section.