Date and time in Pascal
last modified November 18, 2026 Free Pascal 3.2.2
Pascal has no separate date type: a TDateTime is a floating-point
number whose integer part counts days and whose fractional part counts the time
of day. The SysUtils and DateUtils units turn that
number into calendar fields and back, format it for people, and compare and
shift it. This article explains the epoch behind the number, formats a date in
several ways, splits it into year, month, day, hour, minute, second, and
millisecond, does date arithmetic, reads and writes ISO 8601 strings, and
measures how long a loop takes.
TDateTime is a number
The zero point of TDateTime is 30 December 1899 at midnight, the
same epoch that Delphi and the Windows OLE automation types use. A value of 1
is 31 December 1899, a value of 2 is 1 January 1900, and 25569 is 1 January
1970, the Unix epoch. The fractional part is the time divided by 24 hours, so
0.5 is noon and 0.25 is six in the morning. The example below prints the
numeric value of a known date, checks the epoch, and separates the date and
time parts with Int and Frac.
program epoch;
{$mode objfpc}{$H+}
uses SysUtils, DateUtils;
var
D: TDateTime;
begin
D := EncodeDateTime(2026, 11, 18, 14, 5, 9, 250);
WriteLn('as Double: ', FloatToStr(D));
WriteLn('day zero: ', FormatDateTime('yyyy-mm-dd', TDateTime(0)));
WriteLn('1970-01-01: ', Trunc(EncodeDate(1970, 1, 1)));
WriteLn('2026-11-18: ', Trunc(EncodeDate(2026, 11, 18)));
WriteLn('date part: ', FormatDateTime('yyyy-mm-dd', Int(D)));
WriteLn('time part: ', FormatDateTime('hh:nn:ss.zzz', Frac(D)));
end.
EncodeDateTime builds the value from its parts, and
EncodeDate takes only the date. Trunc removes the
time, which is why the two dates print as whole numbers, and Int
returns the same value as a real. Frac keeps the time of day.
Because a day is one unit, subtracting two dates gives the difference in days
directly, and adding 0.5 adds twelve hours.
$ fpc -gl epoch.pas $ ./epoch as Double: 46344.5869126157 day zero: 1899-12-30 1970-01-01: 25569 2026-11-18: 46344 date part: 2026-11-18 time part: 14:05:09.250
Formatting dates and times
FormatDateTime takes a pattern and a TDateTime and
returns a string. The pattern uses fixed letters for the fields: yyyy
is the four-digit year, mm the month, dd the day,
hh the hour, nn the minute, ss the
second, and zzz the millisecond. Names such as dddd
for the weekday and mmmm for the month are taken from the current
locale.
program formatdate;
{$mode objfpc}{$H+}
uses SysUtils, DateUtils;
var
D: TDateTime;
begin
D := EncodeDateTime(2026, 11, 18, 14, 5, 9, 250);
WriteLn(FormatDateTime('yyyy-mm-dd', D));
WriteLn(FormatDateTime('dd/mm/yyyy', D));
WriteLn(FormatDateTime('dddd, d mmmm yyyy', D));
WriteLn(FormatDateTime('hh:nn:ss.zzz', D));
WriteLn(FormatDateTime('yyyy-mm-dd"T"hh:nn:ss', D));
WriteLn(FormatDateTime('yy/mm/dd hh:nn AM/PM', D));
WriteLn(DateToISO8601(D));
end.
Literal text in a pattern is quoted with double quotes, so the T
between the date and the time does not get interpreted as a field.
AM/PM switches the hour to the twelve-hour clock. The
DateToStr, TimeToStr, and DateTimeToStr
functions use the locale settings instead of a pattern; their output changes
with the machine's regional settings, so a stored or parsed format should use
an explicit pattern such as the ISO 8601 line.
$ fpc -gl formatdate.pas $ ./formatdate 2026-11-18 18-11-2026 Wednesday, 18 November 2026 14:05:09.250 2026-11-18T14:05:09 26-11-18 02:05 PM 2026-11-18T14:05:09.250Z
Breaking a value into parts
DecodeDate returns the year, month, and day as separate
Word variables, and DecodeTime returns the hour,
minute, second, and millisecond. The reverse routines are
EncodeDate and EncodeTime. Calendar questions such as
whether a year is a leap year, how many days a month has, and which day of the
week a date falls on are answered by DateUtils.
program parts;
{$mode objfpc}{$H+}
uses SysUtils, DateUtils;
var
D: TDateTime;
Y, M, Day: Word;
H, Min, S, MS: Word;
begin
D := EncodeDateTime(2024, 2, 29, 23, 59, 58, 750);
DecodeDate(D, Y, M, Day);
WriteLn('date: ', Y, '-', M, '-', Day);
DecodeTime(D, H, Min, S, MS);
WriteLn('time: ', H, ':', Min, ':', S, '.', MS);
WriteLn('leap year: ', IsLeapYear(Y));
WriteLn('days in month: ', DaysInAMonth(Y, M));
WriteLn('days in year: ', DaysInAYear(Y));
WriteLn('day of year: ', DayOfTheYear(D));
WriteLn('day of week: ', DayOfWeek(D));
end.
The date is 29 February 2024, a leap day, so IsLeapYear returns
True and February has 29 days. DayOfWeek counts from
Sunday as 1, which makes 5 a Thursday; the ISO convention that starts the week
on Monday is available as DayOfTheWeek. The Word
variables are wide enough for every field, including the millisecond range
0..999.
$ fpc -gl parts.pas $ ./parts date: 2024-2-29 time: 23:59:58.750 leap year: TRUE days in month: 29 days in year: 366 day of year: 60 day of week: 5
Date arithmetic
Because TDateTime is a number, ordinary arithmetic works on it,
but the named routines are clearer and handle the calendar correctly.
IncDay, IncMonth, and IncYear return a
new value shifted by one unit, DaysBetween counts whole days
between two values, and CompareDate compares only the date parts.
The example moves 31 January forward by one month and lands on the last day of
February, because 31 February does not exist.
program arith;
{$mode objfpc}{$H+}
uses SysUtils, DateUtils;
var
A, B: TDateTime;
begin
A := EncodeDate(2026, 1, 31);
B := EncodeDate(2026, 3, 1);
WriteLn('days between: ', DaysBetween(A, B));
WriteLn('A + 1 day: ', FormatDateTime('yyyy-mm-dd', IncDay(A, 1)));
WriteLn('A + 1 month: ', FormatDateTime('yyyy-mm-dd', IncMonth(A, 1)));
WriteLn('A + 1 year: ', FormatDateTime('yyyy-mm-dd', IncYear(A, 1)));
WriteLn('B - A (days): ', FloatToStr(B - A));
WriteLn('earlier: ', CompareDate(A, B) < 0);
if A < B then
WriteLn('A is before B');
end.
The difference between 31 January and 1 March 2026 is 29 days, because 2026 is
not a leap year. IncMonth clamps to 28 February, while
IncYear keeps the day because 2027 is not a leap year either.
The relational operators compare the full values, including the time of day,
which is midnight for both dates here.
$ fpc -gl arith.pas $ ./arith days between: 29 A + 1 day: 2026-02-01 A + 1 month: 2026-02-28 A + 1 year: 2027-01-31 B - A (days): 29 earlier: TRUE A is before B
ISO 8601 strings
ISO 8601 writes the date as yyyy-mm-dd and the time as
hh:nn:ss, separated by T. The format sorts
lexicographically in the same order as the dates, which makes it suitable for
file names, log lines, and configuration files. DateUtils provides
ISO8601ToDate and DateToISO8601 for the conversion.
program iso;
{$mode objfpc}{$H+}
uses SysUtils, DateUtils;
var
D: TDateTime;
begin
D := ISO8601ToDate('2026-11-18T14:05:09');
WriteLn('parsed: ', FormatDateTime('yyyy-mm-dd hh:nn:ss', D));
WriteLn('back: ', DateToISO8601(D));
D := ISO8601ToDate('2026-11-18T14:05:09.250Z', True);
WriteLn('utc: ', FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', D));
end.
The optional Boolean argument tells ISO8601ToDate whether a value
with a time zone designator should be returned as UTC; with True
the trailing Z leaves the clock fields unchanged, while
False converts them to local time. DateToISO8601
appends a Z designator to the value it receives; it does not
convert a local time, so the caller must pass a UTC value if the suffix is to
be accurate. An invalid string does not return a flag: it raises
EConvertError, which the
exceptions article handles with
try..except.
$ fpc -gl iso.pas $ ./iso parsed: 2026-11-18 14:05:09 back: 2026-11-18T14:05:09.000Z utc: 2026-11-18 14:05:09.250
Measuring elapsed time
Now has a resolution of about a millisecond and is adequate for
timing longer operations, while GetTickCount64 reads a monotonic
millisecond counter that is not affected by changes to the system clock. The
DateUtils functions MilliSecondsBetween and
SecondsBetween subtract two TDateTime values and
return whole units.
program timing;
{$mode objfpc}{$H+}
uses SysUtils;
var
StartTick: QWord;
I: Integer;
Sum: Int64;
Elapsed: QWord;
begin
StartTick := GetTickCount64;
Sum := 0;
for I := 1 to 5000000 do
Inc(Sum, I);
Elapsed := GetTickCount64 - StartTick;
WriteLn('sum: ', Sum);
WriteLn('elapsed ms: ', Elapsed);
end.
The loop adds the numbers from 1 to 5,000,000, which gives 12,500,002,500,000
and does not fit in a 32-bit integer, so the accumulator is an
Int64. The measured time was 8 ms on this machine; the exact value
depends on the processor and the compiler options, and a single run is only an
indication. For a reliable measurement, repeat the operation and divide, or
use the -O2 and -O- optimizer settings to compare.
$ fpc -gl timing.pas $ ./timing sum: 12500002500000 elapsed ms: 8
Timing a fixed interval
A fixed interval can be measured without a clock reading at all, by converting the difference of two known values. The next example does that and also checks that a short sleep lasts at least the requested time.
program sleeper;
{$mode objfpc}{$H+}
uses SysUtils, DateUtils;
var
Start: TDateTime;
A, B: TDateTime;
begin
A := EncodeDateTime(2026, 1, 1, 0, 0, 0, 0);
B := EncodeDateTime(2026, 1, 1, 0, 0, 1, 500);
WriteLn('milliseconds: ', MilliSecondsBetween(B, A));
WriteLn('seconds: ', SecondsBetween(B, A));
Start := Now;
Sleep(150);
WriteLn('slept at least 100 ms: ',
MilliSecondsBetween(Now, Start) >= 100);
end.
Sleep suspends the process for at least the requested number of
milliseconds; the operating system may wake it later, which is why the test
asks for a lower bound rather than an exact value. The program has no
TStopwatch: that class belongs to Delphi's System.Diagnostics
unit and is not part of the Free Pascal RTL, so timing code uses
Now, GetTickCount64, or fpgettimeofday.
$ fpc -gl sleeper.pas $ ./sleeper milliseconds: 1500 seconds: 1 slept at least 100 ms: TRUE
Next steps
Dates and times appear in the input and formatted output articles, which parse and print the fields, and in the random numbers article, which seeds the generator from the clock. The exceptions article shows how to recover from an invalid date string, and the scientific simulations article uses elapsed time to compare integration steps.
Source
In this article we treated TDateTime as a day count, formatted it
with patterns, split it into calendar fields, shifted and compared dates, read
and wrote ISO 8601 strings, and measured elapsed time with the monotonic clock.
The series continues with
random numbers in Pascal.
Author
List all Pascal tutorials.