Delphi Dates and Times

AmazonTechnical.gif (2495 bytes)  in   look for  Delphi


A.  Functions, Procedures, Data Structures
B.  Calendar Dates
C.  Date Math
D.  Resources

(bookmark.gif (183 bytes) Bookmark)

A.  Functions, Procedures, Data Structures

Name Description/Example Unit
AccuTime AccuTimer is an highly accuate timer that can display the time all the way down to the last millisecond. AccuTimer can tell how long your windows OS has been running. This Component comes with source code and sample software.
Age Example, including CalculateAge function, to calculate a person's age given two TDate values.  
AlterFileTimeStamp See AlterFileTimeStamp.TXT for an example.  
ApproxPentiumSpeed See GetCycleCount  
Auto Completing Dates Data manipulation:  improve your code, let them type faster
BDE Setting the BDE Date Format from a Delphi Application,1410,20844,00.html

function CenturyOfDate(const DateTime: TDateTime): Integer; 
function CenturyBaseYear(const DateTime: TDateTime): Integer;

Delphi Jedi Code Library, JCLDateTime.Pas unit

CompareFileTime function CompareFileTime(const lpFileTime1, lpFileTime2: TFileTime): Longint; stdcall;

The CompareFileTime function compares two TFileTime values.

Control Panel Applet How to call the TimeDate Windows Control Panel Applet  

function HoursToMSecs(const Hours: Integer): Integer;
function MinutesToMSecs(const Minutes: Integer): Integer;
function SecondsToMSecs(const Seconds: Integer): Integer;

function TimeOfDateTimeToSeconds(const DateTime: TDateTime): Integer;
function TimeOfDateTimeToMSecs(const DateTime: TDateTime): Integer;

function DateTimeToLocalDateTime(const DateTime: TDateTime): TDateTime;
function DateTimeToDosDateTime(const DateTime: TDateTime): TDosDateTime;
function DateTimeToFileTime(const DateTime: TDateTime): TFileTime;
function DateTimeToSystemTime(const DateTime: TDateTime): TSystemTime; overload;

function LocalDateTimeToFileTime(const DateTime: TDateTime): FileTime;
function LocalDateTimeToDateTime(const DateTime: TDateTime): TDateTime;

function DosDateTimeToDateTime(const DosTime: TDosDateTime): TDateTime;
function DosDateTimeToFileTime(const DosTime: TDosDateTime): TFileTime; overload;
function DosDateTimeToSystemTime(const DosTime: TDosDateTime): TSystemTime;
function DosDateTimeToStr(const DateTime: Integer): string;

function FileTimeToDateTime(const FileTime: TFileTime): TDateTime;
function FileTimeToLocalDateTime(const FileTime: TFileTime): TDateTime;
function FileTimeToDosDateTime(const FileTime: TFileTime): TDosDateTime; overload;
function FileTimeToSystemTime(const FileTime: TFileTime): TSystemTime; overload;
function FileTimeToStr(const FileTime: TFileTime): string;

function SystemTimeToDosDateTime(const SystemTime: TSystemTime): TDosDateTime;
function SystemTimeToFileTime(const SystemTime: TSystemTime): TFileTime; overload;
function SystemTimeToStr(const SystemTime: TSystemTime): string;         

 Delphi Jedi Code Library, JCLDateTime
.Pas unit
Unit PJHFileTimes:
  read and set file dates.
Unit PJHDateTimes:
  Unit for datetime converting: TDateTime, UnixTime, FileTime,
  Julian Day (J.D.), Chronological Julian Day (C.J.D.),
  Modified Julian Day (M.J.D.), Truncated Julian Day (T.J.D.),
  Lilian Day (L.D.) (both units)
CopyFileDate Borland's "How to match file date/time stamps" TI 719D
Date Date gets the current date.
Label1.Caption := 'Today is ' + DateToStr(Date);
DateDelta 693594 = Days between 1/1/0001 and 12/31/1899.

Constant used to convert from D1 TDateTimes to those used in D2 and later.

DateSeparator Date separator chacter, e.g., '/' (depends on locale settings) (See also TimeSeparator) SysUtils
DateTimeToFileDate FUNCTION DateTimeToFileDate(DateTime: TDateTime):  Integer;

Convert TDateTime to a DOS date/time value.  The FileAge, FileGetDate, and FileSetDate routines operate on DOS date-and-time values, and the Time field of a TSearchRec used by the FindFirst and FindNext functions contains a DOS date-and-time value.

See FileSetDate example.
See AlterFileTimeStamp.TXT example.

DateTimeToStr DateTimeToStr converts a variable of type TDateTime to a string.
s := DateTimeToStr(Now); See Borland's TI 541D for an example.
DateTimeToString DateTimeToString converts a variable to a string using the specified Format. SysUtils
DateTimeToSystemTime Defines TSystemTime variable given a TDateTime value SysUtils
DateTimeToTimeStamp DateTimeToTimeStamp converts a TDateTime value into the corresponding TTimeStamp value. SysUtils
DateTimeToUNIX In D6 DateUtils unit.  See UseNet Post by Rudy Velthuis with example.

function DateTimeToUnix(const AValue: TDateTime): Int64; 

DateToStr DateToStr converts a variable of type TDateTime to a formatted string.
Label1.Caption := 'Today is ' + DateToStr(Date);

function DayOfDate(const DateTime: TDateTime): Integer; 

Delphi Jedi Code Library, JCLDateTime.Pas unit

DayOfWeek DayOfWeek returns an index of today's day of week.
1=Sunday, 2=Monday, ..., 7=Saturday
Given a day of interest:  year, month, day: WORD;

Compute the number of days since a known Monday, like Jan. 1, 1900:

DaysSince1900 :=
     TRUNC(EncodeDate(year,month,day)) -
     TRUNC(EncodeDate(1900,1,1)) + 1;

Use the MOD function to get the day of the week
(0=Sunday, 1=Monday, ..., 6=Saturday):

DayOfWeek := DaysSince1900 MOD 7;

Note:  ISO-8601 specifies Monday=1, Tuesday=2, ..., Sunday=7.
Therefore,  ISO8601day := (DayOfWeek+5) MOD 7 + 1;
(Thanks to Peter Haas for correcting this formula for me.
See Peter's info and unit at "Datum und Zeit - ISO 8601,"

RM Mentock's UseNet Post about "Doomsday" (28 Feb) and DayOfWeek  
function DaysInMonth(const DateTime: TDateTime): Integer;

Delphi Jedi Code Library, JCLDateTime.Pas unit

DecodeDate DecodeDate breaks TDateTime into Year, Month, and Day values.
TempDate := StrToDate(date);
DecodeDate(TempDate, Year, Month, Day);
RESULT := Format('%4.4d%2.2d%2.2d', [Year, Month, Day]);
DecodeTime See EncodeTime below  
DOSDateTimeToFileTime The DosDateTimeToFileTime function converts MS-DOS date and time values to a 64-bit lpFileTime. Windows
EncodeDate EncodeDate returns a TDateTime type for a specified Year, Month, and Day.
FirstDayOfYear := EncodeDate(TargetYear, 1, 1);
bookmark.gif (183 bytes)EncodeTime EncodeTime returns a TDateTime type for a specified Hour, Min, Sec, and MSec.

FUNCTION TruncatedMinute (VAR DateTime: TDateTime): TDateTime;
    Day         : WORD;
    Hours       : WORD;
    Milliseconds: WORD;
    Minutes     : WORD;
    Month       : WORD;
    Year        : WORD; {will be ignored}
    Seconds     : WORD; {will be ignored}
    MilliSec    : WORD; {will be ignored}
  DecodeDate(DateTime, Year, Month, Day);
  DecodeTime(DateTime, Hours, Minutes, Seconds, MilliSeconds);
  RESULT := EncodeDate(Year, Month, Day) +
  EncodeTime(Hours, Minutes, 0, 0);
END {TruncatedMinute};
ESB Consultancy
Developers of Mathematical & Statistical
Software and Delphi Software.

ESBDates™ v1.1- Large collection of Date & Time Routines to supplement those supplied by SysUtils. Includes TimeZone Calculations, Date Arithmetic, Easter Calculations, etc.  Includes Help File and Full Source.

FileAge FileAge returns the date-and-time stamp of the specified file.

The return value can be converted to a TDateTime value using the FileDateToDateTime function. The return value is -1 if the file does not exist.

StatsLogStamp := FileAge('stats.log');
bookmark.gif (183 bytes)FileDateToDateTime FileDateToDateTime converts a DOS date-time value to TDateTime format.

{See FileGetDate for definition of date1.}
IF   date1 <> date2
  MessageDlg ('A newer program should be copied from ' +
              'the network.' + #$0D +
              'Local Copy Date: ' + 
              FormatDateTime('mm/dd/yy hh:nn:ss',
                 FileDateToDateTime(date1)) + #$0D +
              'Network Copy Date: ' + 
              FormatDateTime('mm/dd/yy hh:nn:ss',
              mtInformation, [mbOK], 0)


Show Windows' Current Version Date/Time
[Only Works in Windows 95/98.  See method 3 for NT below]

Method 1.  "Old" Way for Windows 95/98 -- FirstInstallDateTime

    Data      :  ARRAY[BYTE] OF CHAR;
    DataLength:  INTEGER;

    // Use to extract 4-byte integer from data
    DataValue :  INTEGER  ABSOLUTE Data; 
    Key       :  hKey;
    ValueType :  INTEGER;

// Open the registry key
     0,0, Key) = ERROR_SUCCESS
  DataLength := SizeOf(Data);
  RegQueryValueEx(Key, 'FirstInstallDateTime', 
                  NIL, @ValueType, @Data[0], @DataLength);
  // Sample result:  08/11/2000 08:26
  ShowMessage(FormatDateTime('mm/dd/yyyy hh:nn',

  // Close the registry key

Method 2.  "New" Way for Windows 95/98

procedure TFormIDKey.ButtonDisplayClick(Sender: TObject);
    KeyValue   :  DWORD;
    Registry   :  TRegistry;
  KeyValue := $210000;   // 1/1/1980
  Registry := TRegistry.Create;
    Registry.RootKey := HKEY_LOCAL_MACHINE;
    IF   Registry.OpenKeyReadOnly(
      IF   (Registry.GetDataType('FirstInstallDateTime') = 
           (Registry.GetDataSize('FirstInstallDateTime') = 
            SizeOf(KeyValue) )
      THEN Registry.ReadBinaryData('FirstInstallDateTime',
                                   KeyValue, SizeOf(KeyValue))
  LabelDateTimeValue.Caption :=
    FormatDateTime('mm/dd/yyyy hh:nn:ss', 

Method 3.  Alternative for Windows NT -- InstallDate

    InstallDate:  TDateTime;
    KeyValue   :  DWORD;
    Registry   :  TRegistry;  
. . .
  KeyValue := 0;   // 1/1/1980    
  Registry := TRegistry.Create;
    Registry.RootKey := HKEY_LOCAL_MACHINE;
    IF   Registry.OpenKeyReadOnly(
         'SOFTWARE\Microsoft\Windows NT\CurrentVersion')
    THEN KeyValue := Registry.ReadInteger('InstallDate');
  // Simiilar to UNIX conversion 
  InstallDate := EncodeDate(1970,1,1) + KeyValue/86400;
  LabelDateTimeValue.Caption := FormatDateTime('mm/dd/yyyy hh:nn:ss',
FileGetDate FileGetDate returns a DOS date-time stamp for the specified file.

Handle := FileOpen(FileName, fmOpenRead OR fmShareDenyNone);
DOSStamp := FileGetDate(Handle);
DateTimeStamp := FileDateToDateTime(DOSStamp);

Get a file's date time stamp

FileSetDate FileSetDate sets the DOS time stamp for a specified file.
See AlterFileTimeStamp.TXT for an example.

Peter Below's UseNet Post about setting CreatedDateTime of a file

FileTimeToDOSDateTime The FileTimeToDosDateTime function converts a 64-bit file time to MS-DOS date and time values. Windows
FileTimeToLocalFileTime The FileTimeToLocalFileTime function converts a file time based on the Coordinated Universal Time (UTC) to a local file time. For an example, see FAQ 1930D which shows how to "determine the last access time of a give file."

Jamie Frater's UseNet Post with UnixTimeToDateTime by code by Philippe Ranger showing use of SystemTimeToTzSpecifiedLocalTime

FileTimeToSystemTime The FileTimeToSystemTime function converts a 64-bit file time to system time format.

Delphi 5 Developer's Guide, pp. 291-292

Jamie Frater's UseNet Post with UnixTimeToDateTime by code by Philippe Ranger showing use of SystemTimeToTzSpecifiedLocalTime

FAQ 1930D
Find files and file attributes within a directory.
Determine the last access time of a give file.
FAQ 1930D
FirstDayOfMonth FirstDayOfMonth := EncodeDate(Year, Month, 1);  
FormatDateTime Formats the TDateTime value using the specified format.

LabelMonth.Caption := FormatDateTime('mmmm yyyy', CurrentDate);

LabelSelectedDate.Caption := 
  FormatDateTime('dddd, mmmm d, yyyy   h:nn:ss', CurrentDate);

See other examples:  "Windows' Current Version Date/Time" under FileDateToDateTime

FromNow Ed Dressel's UseNet Post with these suggestions:
OneHourFromNow   := Now + 1/24;
OneMinuteFromNow := Now + 1/(24 * 60);
OneSecondFromNow := Now + 1/(24 * 60 * 60);
ftLastAccessTime Determine the last access time of a given file. FAQ 1930D
bookmark.gif (183 bytes)GetCycleCount

// Adapted from Robert Lee's UseNet Post
// Minimally invasive and accurate down to about 40 cycles.
// Requires Pentium or greater
FUNCTION GetCycleCount:  Int64;   // D4-D5
  DB 0FH
  DB 031H

procedure TForm1.Button1Click(Sender: TObject);
    Start:  Int64;    // D4-D5
    Stop :  Int64;
  Start := GetCycleCount;
  Sleep(2000);   // 2000 milliseconds = 2 seconds
  Stop := GetCycleCount;
  ShowMessage( IntToStr(Stop-Start) )

Results on Pentiums:
120 MHz  240112244
166 MHz  332354144
450 MHz  899102646 

Based on these values, there are approx 1000141 counts/MHz.  This suggests the following function to estimate speed of processor:

FUNCTION ApproxPentiumSpeed:  INTEGER;
    Start:  Int64;    // D4-D5
    Stop :  Int64;
  Start := GetCycleCount;
  Sleep(1000);   // 1000 milliseconds = 1 second
  Stop := GetCycleCount;
  RESULT := ROUND( (Stop-Start) / 1000141)

Also see GetTickCount and QueryPerformanceCounter

GetFileDate Borland's "How to get a file's date and time stamp" TI 541D
GetFileTime The GetFileTime function retrieves the date and time that a file was created, last accessed, and last modified.

Ian Huang's UseNet Post with sample code

GetLocaleChar Peter's examples show how to use GetLocaleChar values for LOCALE_IFIRSTDAYOFWEEK and LOCALE_IFIRSTWEEKOFYEAR, e.g.,


See GetWinLocaleWeekDef function in DTWeeks.pas unit by Peter Haas.

GetLocalTime The GetLocalTime function retrieves the current local date and time. See Borland's  "Getting the time and date in Universal Time" for an example. Windows
FAQ 1157D
GetSystemTime The GetSystemTime function retrieves the current system date and time. The system time is expressed in Coordinated Universal Time (UTC). See Borland's "Getting the time and date in Universal Time" for an example. System
FAQ 1157D
GetSystemTimeAsFileTime The GetSystemTimeAsFileTime function obtains the current system date and time. The information is in Coordinated Universal Time (UTC) format. System
GetSystemTimeAdjustment The GetSystemTimeAdjustment function determines whether the system is applying periodic time adjustments to its time-of-day clock at each clock interrupt, along with the value and period of any such adjustments. Windows
GetThreadLocale See SetLocaleWeekSetting procedure in DTWeek.PAS unit by Peter Haas. 

Peter's examples show how to use GetLocaleChar values for LOCALE_IFIRSTDAYOFWEEK and LOCALE_IFIRSTWEEKOFYEAR, e.g.,


See GetWinLocaleWeekDef function in DTWeeks.pas unit by Peter Haas.

bookmark.gif (183 bytes)GetThreadTimes
(Windows NT/2000 only)
function GetThreadTimes(hThread: THandle; 
  var lpCreationTime, lpExitTime, lpKernelTime,
  lpUserTime: TFileTime): BOOL; stdcall; 

Delphi 5 Developer's Guide, pp. 291-292

Windows 95/98 returns FALSE.

bookmark.gif (183 bytes)GetTickCount

  Start:  DWORD;    // D2-D5
  Stop :  DWORD;
Start := GetTickCount;
Sleep(2000);   // 2000 milliseconds = 2 seconds
Stop := GetTickCount;
  IntToStr(Stop-Start) + ' ' +
  Format( '%.3f', [ (Stop-Start)/1000 ])  + ' seconds')

Sample Output:  2001  2.001 seconds

The GetTickCount function retrieves the number of milliseconds that have elapsed since Windows was started. The internal timer wraps around to zero if Windows is run continuously for approximately 49.7 days. (Editorial:  Can Windows run that long without crashing?  Take a look at MS's Computer Hangs After 49.7 Days.)

Borland's "Timed beeps from the PC speaker," FAQ 1838D

Also, see QueryPerformanceCounter and GetCycleCount

bookmark.gif (183 bytes)GetTimeZoneInformation The GetTimeZoneInformation function retrieves the current time-zone parameters. These parameters control the translations between Coordinated Universal Time (UTC) and local time.  See also TTimeZoneInformation.

Erez Steinberg's UseNet Post about using GetTimeZoneInformation

Read and translate the info in a TTimeZoneInformation record:

PROCEDURE TFormSystemInfo.ShowDateTime;
    TimeZoneInformation: TTimeZoneInformation;

    CASE w OF
      1: RESULT := '1st';
      2: RESULT := '2nd';
      3: RESULT := '3rd';
      4: RESULT := '4th';
      5: RESULT := 'Last';
      ELSE RESULT := 'Unknown'
  END {DayInMonth};

  MemoInfo.Lines.Add(' Current Time ' +
  FormatDateTime('mm/dd/yyyy hh:nn:ss', Now));

  // See pp. 700-702 of "Tomes of Delphi 3: Win32 Core API."

  WITH TimeZoneInformation DO
    IF   StandardDate.wYear = 0
    THEN MemoInfo.Lines.Add(' ' + StandardName + ' Starts ' +
         DayInMonth(StandardDate.wDay) + ' ' +
         LongDayNames[1+StandardDate.wDayofWeek] + ' of ' +
    ELSE MemoInfo.Lines.Add(' ' + StandardName + ' Starts ' +
         Format('%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d',
         [StandardDate.wMonth, StandardDate.wDay,
         StandardDate.wHour, StandardDate.wMinute,

  WITH TimeZoneInformation DO
    IF   DaylightDate.wYear = 0
    THEN MemoInfo.Lines.Add(' ' + DaylightName + ' Starts ' +
         DayInMonth(DaylightDate.wDay) + ' ' +
         LongDayNames[1+DaylightDate.wDayofWeek] + ' of ' +
    ELSE MemoInfo.Lines.Add(' ' + DaylightName + ' Starts ' +
         Format('%2.2d/%2.2d/%4.4 %2.2d:%2.2d:%2.2d',
         [DaylightDate.wMonth, DaylightDate.wDay,
         DaylightDate.wHour, DaylightDate.wMinute,
END {ShowDateTime};

Getting a list of valid time zones from Windows, Borland's FAQ 2700D
Using GetTimeZoneInformation function, FAQ 2630D

IncMonth Function IncMonth(const Date: TDateTime; NumberOfMonths: Integer): TDateTime;

IncMonth returns Date shifted by the specified number of months.
NumberOfMonths parameter can be negative, to return a date N months ago.  If the input day of month is greater than the last day of the resulting month, the day is set to the last day of the resulting month.  Input time of day is copied to the DateTime result.

InstallDate InstallDate (Widows NT) and FirstInstallDateTime (Windows 95/98) are Windows registry keys.  See examples of reading these keys under FileDateToDateTime.  
IsLeapYear Function IsLeapYear(Year: Word): Boolean;

Function that identifies whether specified year is a leap year.

function IsLeapYear(const Year: Integer): Boolean;  overload;
function IsLeapYear(const DateTime: TDateTime): Boolean;  overload; 

Delphi Jedi Code Library, JCLDateTime.Pas unit

ISODateStrToDateTime Graham Harris' UseNet Post with ISODateStrToDateTime function  
Julian Day (Business) A Julian day is the number of the day of the year, e.g., Jan. 1 = 1, Jan.2 = 2, etc, and Dec 31 = 365 (or 366 in a leap year). If Year is a word variable that contains the year of interest, and you want the Julian day for a given Month and Day, also stored in word variables, the Julian day is:

JulianDay :=
     TRUNC(EncodeDate(year,month,day)) -
     TRUNC(EncodeDate(year,1,1)) + 1;

Alternate Solution:

// [Meeus91, p. 65]
// DayOfYear(1978, 11, 14) = 318
// DayOfYear(2000, 11, 14) = 319
  VAR k: WORD;
  IF   IsLeapYear(Year)
  THEN k := 1
  ELSE k := 2;
  RESULT := TRUNC(275*Month/9) - 
                        k*TRUNC( (Month+9)/12 ) + Day - 30
END {DayOfYear};

LastDayInMonth // Last day in month is day before first day of next month
FUNCTION LastDayInMonth(CONST year, month: WORD): TDateTime;
  IF   month = 12
  THEN RESULT := EncodeDate(Year+1, 1, 1) - 1
  ELSE RESULT := EncodeDate(Year, Month+1, 1) - 1

ShowMessage( FormatDateTime('mmmm dd, yyyy',
     LastDayInMonth(SpinEditYear.Value, SpinEditMonth.Value) ));

LocalFileTimeToFileTime The LocalFileTimeToFileTime function converts a local file time to a file time based on the Coordinated Universal Time (UTC).  
LongDateFormat Windows definition of long date format, e.g., 'dddd, MMMM dd, yyyy''. (See also ShortDateFormat) SysUtils
LongDayNames Array of strings containing long day names, e.g., LongDayNames[1] = 'Sunday' and LongDayNames[7] = 'Saturday' (depends on locale settings) (See also ShortDayNames array) SysUtils
LongTimeFormat Windows definition of long time format, e.g., 'h:mm:ss AMPM''. (See also ShortTimeFormat) SysUtils
LongMonthNameToInteger // Requires LongMonthNames from SysUtils
// Returns 1 for 'January' .. 12 for 'December', 0 if invalid
    MonthIndex: INTEGER;
    NotFound : BOOLEAN;
  RESULT := 0;
  NotFound := TRUE;
  MonthIndex := 0;
  WHILE (MonthIndex < 12) AND NotFound DO
    IF   Month = LongMonthNames[MonthIndex]
      NotFound := FALSE;
      RESULT := MonthIndex
SysUtils and efg's function
LongMonthNames Array of strings containing long month names, e.g., LongMonthNames[1] = 'January' and LongMonthNames[12] = 'December' (depends on locale settings) (See also ShortMonthNames array) SysUtils
MonthDays Number of days in a month:
MonthDays[IsLeapYear, MonthNumber]

function MonthOfDate(const DateTime: TDateTime): Integer;  

Delphi Jedi Code Library, JCLDateTime.Pas unit

MSecsPerDay SecsPerDay * 1000 SysUtils
MSecsToTimeStamp (D3) function MSecsToTimeStamp(MSecs: Comp): TTimeStamp;

Call MSecsToTimeStamp to convert MSecs, a number of milliseconds, into the number of days represented, plus the number of milliseconds remaining. The days and milliseconds are expressed as a TTimeStamp value, where the Date field is the number of days and the Time field is the remainder in milliseconds.   (Unclear why Comp type is used in D4 and after when Int64 is available.)

Multimedia Timers Tomes of Delphi:  Win 32 MultiMedia API
Chapter 7, Timers and Joysticks
NextYear 1 + EncodeDate(StrToInt(FormatDateTime('yyyy',Now)),1,1);  
Now Now returns the current date and time. Now = Date + Time SysUtils
bookmark.gif (183 bytes)QueryPerformance
HowTo:  Use QueryPerformanceCounter To Time Code

  Frequency:  Int64;
  Start    :  Int64;    // D4-D5
  Stop     :  Int64;
Sleep(2000);   // 2000 milliseconds = 2 seconds
ShowMessage( IntToStr(Stop-Start) + ' ' +
             IntToStr(Frequency) +  ' ' +
             Format( '%.6f', [ (Stop-Start)/Frequency ])  + 
             ' seconds')

Sample output:  2389176 1193180 2.002360 seconds

JCLCounter.pas unit is part of Delphi Jedi Code Library

See also GetTickCount and GetCycleCount

RDTSC Read Time Stamp Counter  returns the number of clock cycles since the CPU was powered up or reset.   
ReadDate TRegistry method: Retrieves a date value from a specified data value associated with the current key. Registry
ReadDateTime TRegistry method: Retrieves a date and time value from a specified data value associated with the current key. Registry
ReplaceDate (D5) procedure ReplaceDate(var DateTime: TDateTime; const NewDate: TDateTime);

ReplaceDate changes the value of the DateTime parameter so that it has the same date as the NewDate parameter. The time portion of DateTime remains the same. ReplaceDate makes any necessary adjustments for negative dates (before 1900).

ReplaceTime (D5) procedure ReplaceTime(var DateTime: TDateTime; const NewTime: TDateTime);

ReplaceTime changes the value of the DateTime parameter so that it has the same time as the NewTime parameter. The date portion of DateTime remains the same. ReplaceTime makes any necessary adjustments for negative dates. (before 1900)

SecsPerDay 24 * 60 * 60 SysUtils
SetFileTime The SetFileTime function sets the date and time that a file was created, last accessed, or last modified

Peter Below's UseNet Post about setting CreatedDateTime of a file

SetLocalTime The SetLocalTime function sets the current local time and date. System
SetSystemTime The SetSystemTime function sets the current system time and date. The system time is expressed in Coordinated Universal Time (UTC). System
SetSystemTimeAdjustment The SetSystemTimeAdjustment function tells the system to enable or disable periodic time adjustments to its time of day clock. Windows
SetTimeZoneInformation The SetTimeZoneInformation function sets the current time-zone parameters. These parameters control translations from Coordinated Universal Time (UTC) to local time. System
ShortDateFormat Windows definition of short date format, e.g., 'M/d/yy'. (See also LongDateFormat) SysUtils
ShortDayNames Array of strings containing short day names, e.g., ShortDayNames[1] = 'Sun' and ShortDayNames[12] = 'Sat' (depends on locale settings) (See also LongDayNames array) SysUtils
ShortMonthNames Array of strings containing long month names, e.g., ShortMonthNames[1] ='Jan' and ShortMonthNames[12] = 'Dec' (depends on locale settings) (See also LongMonthNames array) SysUtils
ShortTimeFormat Windows definition of short time format, e.g., 'h:mm AMPM''. (See also LongTimeFormat) SysUtils
SLongDayNameSun ..
'Sunday' .. 'Saturday' SysConst
(Delphi 4)
SLongMonthNameJan ..
'January' .. 'December' SysConst
(Delphi 4)
SShortDayNameSun ..
'Sun' .. 'Sat' SysConst
(Delphi 4)
SShortMonthNameJan ..
'Jan' .. 'Dec' SysConst
(Delphi 4)
bookmark.gif (183 bytes)StrToDate

StrToDate converts a string to a date format.

In Delphi 4, the TwoDigitCenturyWindow global variable affects what StrToDate returns.  Here are some examples:

StrToDate( ) of
'01/01/03' '01/01/68' '01/01/50'
1998 0


1903 1968 1950
2002 0


2003 2068 2050
1998 50


2003 1968 1950
2002 50


2003 1968 2050
2020 50


2003 2068 2050
StrToDateTime StrToDateTime converts a string into TDateTime format.
TargetTime := StrToDateTime(TargetDateString + 
              ' ' + TargetTimeString);
TargetTime := StrToDateTime(EditTestTime.Text);
SystemTimeToDateTime Returns TDateTime given a TSystemTime

Jamie Frater's UseNet Post with UnixTimeToDateTime by code by Philippe Ranger showing use of SystemTimeToTzSpecifiedLocalTime

SystemTimeToFileTime The SystemTimeToFileTime function converts a system time to a file time.

Delphi 5 Developer's Guide, pp. 291-292

The SystemTimeToTzSpecificLocalTime function converts a Coordinated Universal Time (UTC) to a specified time zone's corresponding local time.

Jamie Frater's UseNet Post with UnixTimeToDateTime by code by Philippe Ranger showing use of SystemTimeToTzSpecifiedLocalTime

TCalendar Displays month calendar list box for entering/selecting a date.
TCalendar.gif (2474 bytes)
Palette: Samples
  TDate = TYPE TDateTime;
TDatePicker Functionality of the Delphi 3 TDateTimePicker component but with enhanced capabilities and compatibility with Delphi 1.
DatePicker.ZIP with source by Michael Williams
bookmark.gif (183 bytes)TDateTime TYPE
  TDateTime = TYPE Double;

TDateTime is just a floating-point Double! The integer part of the value, INT(x), is the number of days. The fractional part, FRAC(x), is a fractional part of a day. 86400*FRAC(x) yields the number of seconds.

In Delphi 1, Delphi defined a TDateTime as the number of days that have passed since 1/1/0001.  The fractional part represents a fractional part of a day.

In Delphi 2 and later, the TDateTime represents the number of days since 30 December 1899.  A TDateTime of 0 corresponds to 30 Dec 1899; a value of 1 is 31 Dec 1899 = 0 Jan 1900.

A TDateTime can be any date through 31 Dec 9999 (decimal value 2,958,465).   You get the error "invalid argument to date encode" if you try EncodeDate(10000,1,1).

TDateTime values can also be negative.  The decimal value -693593, which can be represented as EncodeDate(1,1,1) or -DateDelta+1, corresponds to 1 Jan 0001. 

The DateDelta constant (693594) can be used to convert from D1 to post-D1 TDateTime values.

A Matter of Time:  Exploring the TDateTime Object, Delphi Informant, Nov 1996

See Borland's "TDateTime component commonly ignores key input," FAQ 966D

bookmark.gif (183 bytes)TDateTimePicker TDateTimePicker is a wrapper around Microsoft's common control.  It uses the Windows date settings, not Delphi's internal ShortDateFormat.

Displays a list box for entering dates or times.

Brian Bushay's UseNet Post about how to force the drop-down calendar to open.  Dave Nottage's UseNet Post about how to  force a TDateTimePicker to drop down programmatically.  See follow-up comments by Frank Aluttis with an improved way to do this.

In D6 and later, use the Format property to change display of date or time.  In D5 and earlier, use the DateTime_SetFormat call, as shown next:

How to have 4-digit years or 24-hour clocks with a TDateTimePicker:

4-Digit Year 
USES CommCtrl;
. . .
// put this in the FormCreate:

mdyyy.gif (1177 bytes) 
// 4-digit year for 3 y's (Microsoft's idea, not mine) 
// or 4 y's.  Example:   3/13/2000
// Use arrow keys to make selections field-by-field 
// (or use drop-down calendar)

dmmmyyyy.gif (3646 bytes)
// Example:  13 Mar 2000
                   pChar('d MMM yyyy'));
// Unclear how to format "Today" above to be 6 Mar 2000.
// Could display dates with DateMode of dmUpDown to 
// suppress calendar:

dmupdown.gif (1174 bytes)

24-Hour Clock

hmmss.gif (1142 bytes) 
// 24-hour clock:  Be sure to set Kind to dtkTime
DateTime_SetFormat(DateTimePickerTest.Handle, pChar('H:mm:ss'));

Instead of using the DateTime_SetFormat function, you can send a message to the control directly:
SendMessage(DateTimePicker1.Handle, DTM_SETFORMAT, 0,

Both Date and Clock in Single Control?

dMMMyyyyHmmss.gif (1284 bytes)
// This appears to work:
                   pChar('d MMM yyyy   H:mm:ss'));
// but you can only edit the date or the time depending 
// on the Kind (dtkTime or dtkDate).

Must a DateTimePicker always show a date?
Alan G Lloyd's UseNet Post about changing the format string to do this.

How can I display a blank date?

D6 Solution:


  CommCtrl; // To set format of TDateTimePicker

// DateTimePicker1.Format is set in IDE to '' (quote-quote)

procedure TForm1.DateTimePicker1Change(Sender: TObject);
  DateTimePicker1.Format := 'M/d/yyy';

procedure TForm1.ButtonClearClick(Sender: TObject);
  DateTimePicker1.Format := ''''''; // ''

procedure TForm1.ButtonStatusClick(Sender: TObject);
  IF DateTimePicker1.Format = ''''''
  THEN ShowMessage('Date is blank')
  ELSE ShowMessage('Date format is ' +

Similar D5 Solution for blank dates without using D6 Format property (also works in D3 and D4).

Date property isn't updated while the calendar is dropped down (D4 and later)
Mark Reichert's UseNet Post about  the OnChange handler for the TDateTimePicker control DT_SelDate

A Better TDateTimePicker

Vanyó Tamás' UseNet Post with a TwoDBDateTimePicker to work as a TDBDateTimePicker

Note about D3 bug with TabStop (by Rick Rogers).

The following routines are from the CommCtrl unit (not to be confused with ComCtrls).  Be sure to add a USES CommCtrl statement to use these functions.  These routines appear to be equivalents of C macros (e.g., DateTime_SetFormat is a C macro for the DTM_SETFORMAT message).

function DateTime_GetSystemTime(hdp: HWND; var pst: TSystemTime): DWORD;

function DateTime_SetSystemTime(hdp: HWND; gd: DWORD; const pst: TSystemTime): BOOL;

function DateTime_GetRange(hdp: HWND; rgst: PSystemTime): DWORD;

function DateTime_SetRange(hdp: HWND; gdtr: DWORD; rgst: PSystemTime): BOOL;

function DateTime_SetFormat(hdp: HWND; sz: PChar): BOOL;
Format Characters (from Microsoft)

Example: (also see the FormCreate in AgeCalculation.TXT)

USES CommCtrl;
. . .
// 4-digit year for 3 y's

                   pChar('H:mm:ss'));   // 24-hour clock

function DateTime_SetMonthCalColor(hdp: HWND; iColor: DWORD; clr: TColorRef): TColorRef;

function DateTime_GetMonthCalColor(hdp: HWND; iColor: DWORD): TColorRef;

function DateTime_GetMonthCal(hdp: HWND): HWND;

procedure DateTime_SetMonthCalFont(hdp: HWND; hfont: HFONT; fRedraw: BOOL);

function DateTime_GetMonthCalFont(hdp: HWND): HFONT;

Microsoft SDK information about Date and Time Picker Controls.

Date Picker Control Does Not Allow 4-Digit Year Input After 2035

Formatting a DateTimePicker Control

Enhancing the TDateTimePicker

Palette: Win32

Units: ComCtrls, CommCtrl
TDateTimePickerLink Non visual Component, that is linking two DateTimePicker controls. If the value of the first DateTimePicker control is higher than the value of the second DateTimePicker control a message is shown and the changed value will be set to the value of the other DateTimePicker control.   
TFileTime TYPE TFileTime =
  dwLowDateTime : DWORD;
  dwHighDateTime: DWORD;

Number of 100-nanosecond intervals since January 1, 1601.

Typecast a TFileTime to an Int64 (D4 or later) to perform arithmetic.

Steve Schafer's UseNet Post about TFileTime to TDateTime

See GetThreadTimes.

Delphi 5 Developer's Guide, pp. 291-292

Section: TFileTime.  see above (Peter Haas' converting function use a lossless direct converting, only a addition and a multiplication)

ThisYear EncodeDate(StrToInt(FormatDateTime('yyyy',Now)),1,1);  
Till TillTaskBar.jpg (1583 bytes)   Till Count-Down Timer  
Time Time returns the current time.
Label1.Caption := 'The time is ' + TimeToStr(Time);
bookmark.gif (183 bytes)Time Zone information

Time Travels:  Of Time Zones, Daylight Savings, and other Delights, Delphi Informant, Feb 2000

Time Zones.  Borland's "Get a list of valid time zones from Windows"
FAQ 2700D

Registry Keys:
HKEY_LOCAL_MACHINE\System\CurrentControlSet\ Control\TimeZoneInformation

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones

TimeAMString Windows definition of 'AM' for given locale SysUtils
Sets/clears the minimum resolution for an application or device driver.  Tomes of Delphi:  Win 32 MultiMedia API, pp. 282-283 mmsystem
TimeGetDevCaps Queries the timer device to determine its resolution.  Tomes of Delphi:  Win 32 MultiMedia API, pp. 281-282 mmsystem
TimeGetSystemTime Retrieves the system time in milliseconds, much like TimeGetTime.  Returns MMTIME structure to return the system time.
Tomes of Delphi:  Win 32 MultiMedia API, pp. 276-278
TimeGetTime Retrieves the system time in milliseconds.  No parameters and returns DWORD.  Wraps every 49.71 days.  In NT the default precision can be 5 ms or more, so use QueryPerformanceCounter and Query Performance Frequency instead.  Tomes of Delphi:  Win 32 MultiMedia API, pp. 278-279 mmsystem
TimePMString Windows definition of 'PM' for given locale SysUtils
Timer "Thread based timer component" from UseNet Post by Carl Caulkett  
TimeSeparator Time separator chacter, e.g., ':' (depends on locale settings) (See also DateSeparator) SysUtils
Starts/cancels a specified timer event.  Tomes of Delphi:  Win 32 MultiMedia API, pp. 279-281 mmsystem
TimeStateToDateTime Returns TDateTime for given TTimeStamp SysUtils
TimeStampToMSecs (D3) function TimeStampToMSecs(const TimeStamp: TTimeStamp): Comp;

Converts a TTimeStamp value into an absolute number of milliseconds.  (Unclear why Comp type is used in D4 and D5 when Int64 is available.)

TimeToStr TimeToStr returns a string from a TDateTime variable. SysUtils
TMonthCalendar (D4) Delphi's TMonthCalendar will show several months, based on its size.  (Win32 tab)  
TSystemTime TYPE TSystemTime =
  wYear     : WORD;
  wMonth    : WORD;
  wDayOfWeek: WORD;
  wDay      : WORD;
  wHour     : WORD;
  wMinute   : WORD;
  wSecond   : WORD;
  sMilliseconds: WORD

Delphi 5 Developer's Guide, pp. 291-292

TTime TTime = TYPE TDateTime Controls

See also GetTimeZoneInformation

TimeZoneInformation = 
    Bias: Longint;
    StandardName: array[0..31] of WCHAR;
    StandardDate: TSystemTime;
    StandardBias: Longint;
    DaylightName: array[0..31] of WCHAR;
    DaylightDate: TSystemTime;
    DaylightBias: Longint;
TTimePanel Component for selecting a range in time. Capable of selecting a range no longer than 24 hours including ability to select time across the midnight line.  
TTimeStamp TYPE TTimeStamp =
  Time: Integer;
  Date: Integer;
bookmark.gif (183 bytes)TwoDigitCentury
VAR TwoDigitYearCenturyWindow: Word = 0;    // New in D4

From SysUtils Source:
"Determines what century is added to two digit years when converting string dates to numeric dates. This value is subtracted from the current year before extracting the century.  This can be used to extend the lifetime of existing applications that are inextricably tied to 2 digit year data entry. The best solution to Year 2000 (Y2k) issues is not to accept 2 digit years at all - require 4 digit years in data entry to eliminate century ambiguities."

Bill Todd's (Team B) UseNet Post explaining usage

See StrToDate above.

bookmark.gif (183 bytes)UnixDateTimeTo
Jamie Frater's UseNet Post with UnixTimeToDateTime by code by Philippe Ranger showing use of SystemTimeToTzSpecifiedLocalTime

From Usenet Post by Finn Tolderlund:
FUNCTION UnixDateTimeToDelphiDateTime(UnixDateTime: LongInt): TDateTime;
  Result := EncodeDate(1970, 1, 1) + 
            (UnixDateTime / 86400); {86400=No. of secs. per day}

UNIXtoDateTime In D6 DateUtils unit.  See UseNet Post by Rudy Velthuis with example.

function UnixToDateTime(const AValue: Int64): TDateTime; 

VarFromDateTime Returns Variant given TDateTime System
VarToDateTime Returns TDateTime given Variant
See Borland's "Converting strings to dates"
FAQ 3006D
Borland's "Detecting if the system time has been changed" FAQ 2020D
Week Number Borland's FAQ 1822D "How can I determine the week number of a given day in the year?"  (The values returned by this FAQ may be useful for some application but are not ISO standard.)

Poul Dige's UseNet Post with WeekNumber function

function ISOWeekNumber(const DateTime: TDateTime; 
                       var YearOfWeekNumber: Integer): Integer;
Delphi Jedi Code Library, JCLDateTime.Pas unit

Finn Tolderlund's UseNet Post with DateToWeek function

Info over different definitions and two lists, that list the used definition sorted by country resp. grouped by definition

Week number unit, which can calculate a week number by definition,
inclusive the UK Inland Revenue Tax Weeks

Getting the date range of a given week number

  SysUtils;  // DayOfWeek, DecodeDate, EncodeDate

// Returns Week Number for a given TDateTime.
// Assumes a Week Starts on Monday.
FUNCTION WeekNumber(TargetDate: TDateTime): INTEGER;
    MondayIndex = 2;  // Sunday = 1
    Year       :  WORD;
    Month      :  WORD;
    Day        :  WORD;
    MondayWeek1:  TDateTime;
  DecodeDate(TargetDate, Year, Month, Day);
  MondayWeek1 := EncodeDate(Year, 1, 1);
  WHILE DayOfWeek(MondayWeek1) <> MondayIndex DO
    MondayWeek1 := MondayWeek1 - 1;
  RESULT := ((TRUNC(TargetDate - MondayWeek1) DIV 7) MOD 52) + 1

Frederic Guillen, E-Mail:
Used with permission. (Rewritten to use English mnemonics)

Windows Current Version See CurrentVersion example under FileDateToDateTime  
WorkingDays Function to return the number of working days (or school days) between two dates in UseNet Post by Philippe Ranger  
WriteDate TRegistry method: Stores a date value in a specifically named data value associated with the current key. Registry
WriteDateTime TRegistry method: Stores a datetime value in a specifically named data value associated with the current key. Registry
function YearOfDate(const DateTime: TDateTime): Integer; 

Delphi Jedi Code Library, JCLDateTime.Pas unit


B.  Calendar Dates

Function Name Description Source(s)
badluk Friday the 13th when the moon is full recipes =
Numerical Recipes Pascal shareware version
caldat calendar date from Julian day number recipes
Easter calculate date of Easter function EasterSunday(const Year: Integer): TDateTime;
Delphi Jedi Code Library, JCLDateTime.Pas unit

Lars Ladingkaer's UseNet Post

UDDF, Section 12, Item 1
Unofficial Delphi Developers FAQ:

Easter for years 1875 to 2124

flmoon calculate phases of the moon recipes
julday Julian day number from calendar date recipes
TMoon Component Phases of the moon Andreas Hörstemeier's TMoon:

C.  Date Math

  dt, newdt:  TDateTime;
dt := EncodeDate(1999, 12, 25) +  EncodeTime(20, 5, 30, 0);
Operation Units


Date Math

25 Dec 1999, 20:05:30
Addition Years y := 25 {years}; newdt := IncMonth(dt, y*12 {months/year}); 25 Dec 2024, 20:05:30
  Weeks w := 8 {weeks}; newdt := dt + 7 {days/week}*w; 19 Feb 2000, 20:05:30
  Months m := 2 {months}; newdt := IncMonth(dt, m); 25 Feb 2000, 20:05:30
  Days d := 120 {days}; newdt := dt + d; 23 Apr 2000, 20:05:30
  Hours h := 50 {hours}; newdt := dt + h / 24 {hours/day}; 27 Dec 1999, 22:05:30
  Minutes m : 90 {minutes}; newdt := dt + m / 1440 {minutes/day}; 25 Dec 1999, 21:35:30
  Seconds s := 137 {secs}; newdt := dt + s / 86400 {seconds/day}; 25 Dec 1999, 20:07:47
Subtraction same as above but change "+" to "-"

ShowMessage( FormatDateTime('dd mmm yyyy, hh:nn:ss', newdt) );

D.  Resources

Adrock Components AlarmList, Analogue Clock, Date/Time Suite, Date Function Class
Ardbcaln Data and non-data aware calendar.
Astronomical Dates and Times Astronomical Information (Eclipses, Dates of Equinox and Solstice, Dates of Easter) 

Oliver Montenbruck and Thomas Pfleger, Astronomy on the Personal Computer (3rd edition), Springer-Verlag, 1998.  (Includes disk with Turbo Pascal 6 code)

Jean Meeus, Astronomical Algorithms, Willmann-Bell, Inc., 1991.
Chapter   7:  Julian Day
Chapter   9:  Dynamical Time and Universal Time
Chapter 11:  Sideral Time at Greenwich
Chapter 27:  Equation of Time (including equinoxes and solstices)

The Astronmical Almanac for the Year 2000 published by U.S. Naval Observatory/U.K. Royal Greenwich Observatory

Book CompanionToTheYear.JPG (7664 bytes)  The Oxford Companion to the Year
Calendars Calendars through the ages

Calendars and calendar-related utilities

Clipper Functions: Date Functions Functions
Components Components

Calendar component suite.  Specializing in the quick selection of a period - left click the start date and right click the end   date, or drag a range.

Date Stamp Algorithms Alfresco: Date Stamp.  Julian Bucknall shows us easy and efficient ways to work with business dates, including business date arithmetic, with positively no Y2K problems!
Delphi Magazine, July 1999
Dates and Times Delphi in a Nutshell,  pp. 524-531
Dates and Times SWAG Software Archive Group:  60+ routines (requires Reader)
Delphi Pages
Determine the last access time of a given file Borland's FAQ 1930D
ESBDates Collection of Date/Time routines aimed to supplement those supplied with SysUtils. Designed for Delphi 3 and 4 (but should work fine with Delphi 2). Includes Help File and Full Source.  Freeware.

International Standard ISO 8601

E-mail from Ian Galpin with ISO 8601 Info and links

The second edition of ISO 8601:

A Summary of the International Standard Date and Time Notation 

Date and Time Formats

Datum und Zeit - ISO 8601 by Peter Haas

Campaign to get the Internet World to use the International Date Format ISO 8601 

International Currency, Date, and Time Formats 

Kronos Easy access to calendar data, including, Christmas, Easter, etc.
Rxlib DataConv Unit: TTimeFormat, TDateTimeFormat class

DateUtil Unit: CurrentYear, IsLeapYear, DaysPerMonth, FirstDayOfPrevMonth, LastDayOfPrevMonth, ExtractDay, ExtractMonth, ExtractYear, IncDate, IncDay, IncYear, ValidDate, DateDiff, MonthsBetween, DaysInPeriod, DaysBetween, IncTime, IncHour, IncMinute, IncSecond, IncMSec, CutTime, GetDateOrder, MonthFromName, StrToDateDef, StrToDateFmt, StrToDateFmtDef, DefDateFormat, DefDateMask, FormatLongDate, FormatLongDateTime

MaxMin Unit: MaxDateTime, MinDateTime

PickDate Unit: SelectDate, SelectDateStr, CreatePopupCalendar, SetupPopupCalendar
Manipulation of Dates Manipulation de dates (French)

TMoon component shows phases of the moon

Orbital Decisions Calendar Component 
Dr. J.R. Stockton's Date & Time Information
SysTools commercial product has date/time validation routines. Good till 3999!
Time Synchronization Server 
Understanding Julian Dates by Tom Wolken in the August 1998 Delphi Developer's Journal, pp. 7-11
Look for JulDat1.PAS in the at
U.S. Naval Observatory Time Service Department U.S. Naval Observatory, Washington, DC  Time, Time zones, Date, Counters. 

Links Verified 2000-Feb-21
Updated 2003-07-05

since 1998-Nov-01

[Note:  Dates above are in ISO 8601 Format]